示例#1
0
文件: discofs.c 项目: laevar/discofs
/*! Main
@param argc number of arguments
@param argv arguments
 @return fuse_main()s return value
*/
int main(int argc, char **argv)
{
    /* return value of fuse_main() */
    int ret;

    /* for signal handling */
    struct sigaction sig;

    /* argument handling */
    struct fuse_args args = FUSE_ARGS_INIT(argc, argv);

    /* file name for database */
    char *db_file;


    /*------------------------*
     * install signal handler *
     *------------------------*/

    /* set handling function */
    sig.sa_handler = sig_handler;

    /* set (no) flags */
    sig.sa_flags = 0;

    /* don't ignore any signal */
    sigemptyset(&sig.sa_mask);

    /* install signal handler for USR1 and USR2 */
    sigaction(SIGUSR1, &sig, NULL);
    sigaction(SIGUSR2, &sig, NULL);


    /*------------------*
     * handle arguments *
     *------------------*/

    if (fuse_opt_parse(&args, &discofs_options, discofs_opts, discofs_opt_proc) == -1)
        return EXIT_FAILURE;

    /* after option parsing, remote mount point must be set */
    if (!REMOTE_ROOT)
    {
        fprintf(stderr, "no remote filesystem given\n");
        return EXIT_FAILURE;
    }

    /* a mount point for discofs must also be set */
    if (!discofs_options.discofs_mp)
    {
        fprintf(stderr, "no mount point given\n");
        return EXIT_FAILURE;
    }

    /* add "use_ino" to display inodes in stat(1)*/
    fuse_opt_add_arg(&args, "-ouse_ino");


    /*---------------*
     * set UID / GID *
     *---------------*/

    /* set GID first since permissions might not be
       sufficient if UID was set beforehand */
    if (discofs_options.gid)
    {
        VERBOSE("setting gid to %d\n", discofs_options.gid);
        if (setgid(discofs_options.gid))
        {
            perror("setting gid");
            return EXIT_FAILURE;
        }
    }
    if (discofs_options.uid)
    {
        VERBOSE("setting uid to %d\n", discofs_options.uid);
        if (setuid(discofs_options.uid))
        {
            perror("setting uid");
            return EXIT_FAILURE;
        }
    }


    /*--------------------*
     * initialize logging *
     *--------------------*/

    /* if -d is specified, override logging settings */
    if (discofs_options.debug)
        log_init(LOG_DEBUG, NULL);
    else
        log_init(discofs_options.loglevel, discofs_options.logfile);



    /*=========================*
     * INITIALIZE CACHE AND DB *
     *=========================*/

    /* compute data root if not passed as option */
    if (!discofs_options.data_root)
        discofs_options.data_root = paths_data_root(REMOTE_ROOT);

    if (!is_dir(discofs_options.data_root))
    {
        if (mkdir_rec(discofs_options.data_root))
            FATAL("failed to create data directory %s\n", discofs_options.data_root);
    }


    /*----------------------*
     * initialize cache dir *
     *----------------------*/

    /* set cache dir */
    CACHE_ROOT = join_path(discofs_options.data_root, "cache");

    /* store length of cache root (to save a few hundred strlen() calls)  */
    CACHE_ROOT_LEN = strlen(CACHE_ROOT);

    /* delete cache if "clear" specified */
    if (discofs_options.clear)
    {
        VERBOSE("deleting cache\n");
        rmdir_rec(CACHE_ROOT);
    }

    /* create cache root if needed */
    if (!is_dir(CACHE_ROOT))
    {
        if (mkdir(CACHE_ROOT, S_IRWXU) != 0)
            FATAL("failed to create cache directory %s\n", CACHE_ROOT);
    }


    /*---------------------*
     * initialize database *
     *---------------------*/

    /* set db filename */
    db_file = join_path(discofs_options.data_root, "db.sqlite");

    /* create database file if it doesn't exist  */
    int fd = open(db_file, (O_RDONLY | O_CREAT), (S_IRUSR | S_IWUSR));
    if (fd == -1)
    {
        perror(db_file);
        FATAL("couldn't open or create database file\n");
    }
    close(fd);

    /* initialize tables etc */
    db_init(db_file, discofs_options.clear);

    /* try to load filesystem features from DB */
    if (db_cfg_get_int(CFG_FS_FEATURES, &discofs_options.fs_features))
    {

        /* if loading failed, try to determine them */
        if (is_mounted(REMOTE_ROOT) && is_reachable(discofs_options.host))
        {
            if (test_fs_features(&discofs_options.fs_features))
            {
                ERROR("failed to test remote fs features\n");
                discofs_options.fs_features = 0;
            }
            /* test succeeded, store value for next time */
            else
                db_cfg_set_int(CFG_FS_FEATURES, discofs_options.fs_features);
        }
        /* nag and assume that no features available (but don't save that) */
        else
        {
            ERROR("could not determine remote fs features");
            discofs_options.fs_features = 0;
        }
    }


    /*------------------*
     * initialize stuff *
     *------------------*/
    #define INIT(name)                          \
        if (name ## _init())                    \
            FATAL("error initializing " #name)
    INIT(lock);
    INIT(sync);
    INIT(job);
    #undef INIT


    /*----------------------*
     * print options to log *
     *----------------------*/
    log_options(LOG_VERBOSE, discofs_options);


    /*-----------------*
     * run fuse_main() *
     *-----------------*/
    ret = fuse_main(args.argc, args.argv, &discofs_oper, NULL);


    /*------*
     * exit *
     *------*/

    lock_destroy();
    sync_destroy();
    job_destroy();

    /* free arguments */
    fuse_opt_free_args(&args);

    /* close database connection */
    db_destroy();


    /* end logging */
    INFO("exiting\n");
    log_destroy();


    /* return fuse_main()s return value */
    return ret;
}
示例#2
0
int main(
    int argc,
    char **argv)
{
    int ret = EXIT_SUCCESS;
    bool done_db_init = false;
    bool done_db_thread_init = false;
    dbconn * db = NULL;

    bool first_time;
    bool force_update = false;
    bool update_had_changes;
    serial_number_t previous_serial;
    serial_number_t current_serial;

    if (argc < 1 || argc > 2)
    {
        fprintf(stderr,
                "Usage: %s [<next serial number>]\n",
                argv[0]);
        fprintf(stderr, "\n");
        fprintf(stderr,
                "The next serial number should only be specified in test mode.\n");
        return EXIT_FAILURE;
    }

    OPEN_LOG("rtr-update", LOG_USER);

    if (!my_config_load())
    {
        LOG(LOG_ERR, "can't load configuration");
        return EXIT_FAILURE;
    }

    // initialize the database connection
    if (!db_init())
    {
        LOG(LOG_ERR, "Could not initialize database program.");
        ret = EXIT_FAILURE;
        goto done;
    }
    done_db_init = true;

    if (!db_thread_init())
    {
        LOG(LOG_ERR, "Could not initialize database thread.");
        ret = EXIT_FAILURE;
        goto done;
    }
    done_db_thread_init = true;

    db = db_connect_default(DB_CLIENT_RTR);
    if (db == NULL)
    {
        LOG(LOG_ERR,
            "Could not connect to the database, check your config "
            "file.");
        ret = EXIT_FAILURE;
        goto done;
    }


    if (!db_rtr_has_valid_session(db))
    {
        return EXIT_FAILURE;
    }

    // Get the previous serial number.
    switch (db_rtr_get_latest_sernum(db, &previous_serial))
    {
        case GET_SERNUM_SUCCESS:
            first_time = false;
            // previous_serial was set by db_rtr_get_latest_sernum
            break;

        case GET_SERNUM_NONE:
            first_time = true;
            // Set previous_serial to a pseudo-random number
            srandom((unsigned int)time(NULL));
            previous_serial = (serial_number_t)random();
            break;

        case GET_SERNUM_ERR:
        default:
            LOG(LOG_ERR, "Error finding latest serial number.");
            ret = EXIT_FAILURE;
            goto done;
    }

    if (!db_rtr_delete_incomplete_updates(db))
    {
        LOG(LOG_ERR, "Error deleting incomplete updates.");
        ret = EXIT_FAILURE;
        goto done;
    }

    // Get/compute the current serial number.
    if (argc > 1)
    {
        force_update = true;
        if (sscanf(argv[1], "%" SCNSERIAL, &current_serial) != 1)
        {
            fprintf(stderr,
                    "Error: next serial number must be a nonnegative integer\n");
            return EXIT_FAILURE;
        }
    }
    else
    {
        // NOTE: this relies on unsigned integer wrap-around to zero
        current_serial = previous_serial + 1;
    }

    // Make sure we're not about to overwrite current_serial, create a
    // loop, or start a diverging history, even though these should be
    // *really* unlikely.
    if (!first_time &&
        !db_rtr_good_serials(db, previous_serial, current_serial))
    {
        if (argc > 1)
        {
            LOG(LOG_ERR,
                "Error: rtr_update is full or in an unusual state, "
                "or the specified next serial number already "
                "exists.");
        }
        else
        {
            LOG(LOG_ERR,
                "Error: rtr_update table is either full or in an "
                "unusual state.");
        }

        ret = EXIT_FAILURE;
        goto done;
    }

    if (!db_rtr_insert_full(db, current_serial))
    {
        LOG(LOG_ERR, "Could not copy current RPKI state.");
        ret = EXIT_FAILURE;
        goto done;
    }

    if (!first_time &&
        !db_rtr_insert_incremental(db, previous_serial, current_serial))
    {
        LOG(LOG_ERR, "Could not compute incremental changes.");
        ret = EXIT_FAILURE;
        goto done;
    }

    if (first_time)
    {
        update_had_changes = true;
    }
    else
    {
        switch (db_rtr_has_incremental_changes(db, current_serial))
        {
            case 1:
                update_had_changes = true;
                break;

            case 0:
                update_had_changes = false;
                break;

            case -1:
            default:
                LOG(LOG_ERR,
                    "Error determining if there were any changes.");
                ret = EXIT_FAILURE;
                goto done;
        }
    }

    if (update_had_changes || force_update)
    {
        // Make the new serial number available for use.
        if (
            !db_rtr_insert_update(db, current_serial, previous_serial,
                first_time))
        {
            LOG(LOG_ERR, "Error making updates available.");
            ret = EXIT_FAILURE;
            goto done;
        }
    }
    else
    {
        LOG(LOG_INFO,
            "Data had no changes since the last update, so no update "
            "was made.");

        // The new data in rtr_full is useless, so delete it.
        if (!db_rtr_delete_full(db, current_serial))
        {
            LOG(LOG_ERR, "Error deleting duplicate data in rtr_full.");
            ret = EXIT_FAILURE;
            goto done;
        }

        // there's nothing to delete from rtr_incremental
    }

    // clean up all the data no longer needed
    // save last two full updates so that no problems at transition
    // (with client still receiving data from previous one)
    //
    // NOTE: The order of these updates and deletes is important.
    // All data must be marked as unusable according to rtr_update
    // before it is deleted from rtr_full or rtr_incremental.
    if (
        !db_rtr_ignore_old_full(
            db, current_serial, previous_serial) ||
        !db_rtr_delete_old_full(
            db, current_serial, previous_serial) ||
        !db_rtr_delete_old_update(
            db, current_serial, previous_serial) ||
        !db_rtr_ignore_old_incremental(db) ||
        !db_rtr_delete_old_incremental(db) ||
        false)
    {
        LOG(LOG_ERR, "Error cleaning up old data.");
        ret = EXIT_FAILURE;
        goto done;
    }


done:

    if (db != NULL)
    {
        db_disconnect(db);
    }

    if (done_db_thread_init)
    {
        db_thread_close();
    }

    if (done_db_init)
    {
        db_close();
    }

    config_unload();

    CLOSE_LOG();

    return ret;
}
示例#3
0
文件: core.c 项目: holdur/oraculo
/*======================================
 *	CORE : MAINROUTINE
 *--------------------------------------*/
int main (int argc, char **argv)
{
	{// Inicializa os argumentos do programa
		char *p1 = SERVER_NAME = argv[0];
		char *p2 = p1;
		while ((p1 = strchr(p2, '/')) != NULL || (p1 = strchr(p2, '\\')) != NULL)
		{
			SERVER_NAME = ++p1;
			p2 = p1;
		}
		arg_c = argc;
		arg_v = argv;
	}

// Não precisamos chamar o malloc_init se o Memory Manager não está ativo [Keoy]
#ifdef USE_MEMMGR
	malloc_init(); // needed for Show* in display_title() [FlavioJS]
#endif

#ifdef MINICORE // minimalist Core
	display_title();
	#ifndef _WIN32
		usercheck();
	#endif
	do_init(argc,argv);
	do_final();
#else// not MINICORE
	set_server_type();	// Define o tipo de servidor (função exclusiva de cada servidor)
	display_title();	// Mostra o título
	// Não precisamos verificar se estamos em root se não estamos em um sistema WIN32 [Keoy]
	#ifndef _WIN32
		usercheck();
	#endif
	db_init();
	signals_init();

	timer_init();
	socket_init();
	plugins_init();

	do_init(argc,argv);	// Inicializa as funções do servidor
	plugin_event_trigger(EVENT_ATHENA_INIT); // Evento inicial dos plugins

	{// Ciclo principal do servidor
		int next;
		// Enquanto a runflag for verdadeira (1) o servidor rodará, do contrário entrará em processo de finalização
		while (runflag) {
			next = do_timer(gettick_nocache());
			do_sockets(next);
		}
	}

	plugin_event_trigger(EVENT_ATHENA_FINAL); // Evento final dos plugins
	do_final();

	timer_final();
	plugins_final();
	socket_final();
	db_final();
#endif

// Não precisamos chamar o malloc_init se o Memory Manager não está ativo [Keoy]
#ifdef USE_MEMMGR
	malloc_final();
#endif

	return 0;
}
示例#4
0
文件: wtable.c 项目: Maxlander/ipush
/* 
 * initialize wtable 
 * */
WTABLE *wtable_init(char *dir)
{
    char path[WT_PATH_MAX], *p = NULL;
    struct stat st = {0};
    WTABLE *w = NULL;
    int n = 0;

    if(dir && (w = (WTABLE *)xmm_mnew(sizeof(WTABLE))))
    {
        n = sprintf(path, "%s/%s", dir, WT_LOG_NAME);
        force_mkdir(path);
        p = path;
        LOGGER_INIT(w->logger, p);
        /* state */
        n = sprintf(path, "%s/%s", dir, WT_STATE_NAME);
        if((w->statefd = open(path, O_CREAT|O_RDWR, 0644)) <= 0
                || fstat(w->statefd, &st) != 0)
        {
            if(w->statefd > 0) close(w->statefd);
            FATAL_LOGGER(w->logger, "open state file[%s] failed, %s",
                    path, strerror(errno));
            _exit(-1);
        }
        else
        {
            if(st.st_size < sizeof(WSTATE)
                    && ftruncate(w->statefd, sizeof(WSTATE)) != 0)
            {
                _exit(-1);
            }
            if((w->state = (WSTATE *)mmap(NULL, sizeof(WSTATE),
                            PROT_READ|PROT_WRITE, MAP_SHARED, w->statefd, 0)) == NULL
                    || w->state == (void *)-1)
            {
                FATAL_LOGGER(w->logger, "mmap state failed, %s", strerror(errno));
                _exit(-1);
            }
            if(st.st_size < sizeof(WSTATE))
                memset(((char *)w->state + st.st_size), 0, sizeof(WSTATE) - st.st_size);
        }
        w->workers = w->state->workers;
        memset(w->workers, 0, sizeof(WORKER) * W_WORKER_MAX);
        w->state->nworkers = 0;
        w->state->conn_total = 0;
        n = sprintf(path, "%s/%s", dir, WT_MDB_DIR);
        w->mdb = db_init(path, DB_USE_MMAP);
        /* mmtrie */
        n = sprintf(path, "%s/%s", dir, WT_MAP_NAME);
        if((w->map = mmtrie_init(path)) == NULL) _exit(-1);
        /* appmap */
        n = sprintf(path, "%s/%s", dir, WT_APPS_NAME);
        if((w->appmap = mmtree64_init(path)) == NULL) _exit(-1);
        mmtree64_use_all(w->appmap);
        /* logger & mutex & mtree & mqueue */
        if((w->queue = mqueue_init()) == NULL) _exit(-1);
        if((w->mtree = mtree_init()) == NULL) _exit(-1);
        w->whitelist = mtree_new_tree(w->mtree);
        //MQ(w->queue)->logger = w->logger;
        MUTEX_INIT(w->mutex);
    }
    return w;
}
示例#5
0
void main(void)
{
	u32 rootfs;
	char *rfs_txt;
	u32 image = 0;
	struct jffs2_raw_inode *node, *mfg_node;
	char *cmdline = 0, *altcmdline = 0;
	u32 kernel_nand_addr = 0, alt_kernel_nand_addr = 0;
	int board_id;
	int done = 0;
	u32 ret = 0;

#ifdef CPU_LF1000
	/* disable the USB controller */
	BIT_SET(REG16(LF1000_UDC_BASE+UDC_PCR), PCE);
#endif
	adc_init();
	board_id = load_board_id();
	display_backlight(board_id);
	clock_init();
	db_init();
	display_init();
	fbcon_init();
	db_displaytee(1);
	
	db_puts("************************************************\n");
	db_puts("*                                              *\n");
	db_puts("* OpenDidj lightning-boot 1.1  /  12 Mar 2010  *\n");
	db_puts("*                                              *\n");
	db_puts("************************************************\n");
	db_puts("\n\n");
	

#ifdef CONFIG_MACH_LF_LF1000
	/* now that backlight is on, see if we have enough battery to boot */
	if(gpio_get_val(LOW_BATT_PORT, LOW_BATT_PIN) == 0 && 
		ADC_TO_MV(adc_get_reading(LF1000_ADC_VBATSENSE)) < BOOT_MIN_MV){
		db_puts("PANIC: battery voltage too low!\n");
		die();
	}
#endif /* CONFIG_MACH_LF_LF1000 */
#ifdef UBOOT_SUPPORT
	if(((REG32(LF1000_GPIO_BASE+GPIOCPAD) & BUTTON_MSK) == BUTTON_MSK)) {
		do {
			db_puts("xmodem download mode\n");
			timer_init();
			offset = 0;
			xmodemInit(db_putchar,db_getc_async);
			tmr_poll_start(2000);
			db_puts("Switch to 115200 baud and press any button\n");
			db_puts("to start XModem download...\n");
	/* set the baud rate */
#define UART16(r)       REG16(LF1000_SYS_UART_BASE+r)
	UART16(BRD) = 1; /* FIXME (for now "1"  sets 115200 baud , "11" sets 19200 baud) */
	UART16(UARTCLKGEN) = ((UARTDIV-1)<<UARTCLKDIV)|(UART_PLL<<UARTCLKSRCSEL);
			if(tfs_load_summary(sum_buffer, BOOT0_ADDR) != 0) {
				db_puts("trying BOOT1\n");
				if(tfs_load_summary(sum_buffer, BOOT1_ADDR)) {
					db_puts("u-boot not found\n");
					break;
				}
			}
			while (!done)
			{			
				if (tmr_poll_has_expired()){
					if(((REG32(LF1000_GPIO_BASE+GPIOCPAD) & BUTTON_MSK) != BUTTON_MSK)) 
					{
						db_displaytee(0);
						ret = xmodemReceive(ubcopy);
						db_displaytee(1);
						if ( ret >= 0 ) break;
					}
					if (ret == -1) 
					db_puts("XMODEM_ERROR : REMOTECANCEL\n");
					
					if (ret == -2)
					db_puts("XMODEM_ERROR : OUTOFSYNC\n");
					
					if (ret == -3)
					db_puts("XMODEM_ERROR : RETRYEXCEED\n");
					if ( ret < 0 ) continue;
	
					/*		
					db_puts("Loaded : ");
					db_int(ret);
					db_puts("bytes\n");
					*/
					}
			}
			
			db_puts("\n\nXModem download complete.\n");
			db_puts("Transferring control to U-Boot.\n");
		
			/* jump to u-boot */
			((void (*)( int r0, int r1, int r2))UBOOT_ADDR) 
				(0, MACH_TYPE_LF1000, 0);
			
			/* never get here! */
			die();
		} while(0);
	}
#endif /* UBOOT_SUPPORT */
 
	/* Set up the kernel command line */

	/* read entire /flags partition */
	nand_read(fs_buffer, BOOT_FLAGS_ADDR, BOOT_FLAGS_SIZE);

	/* find rootfs file */
	node = jffs2_cat((char *)fs_buffer, BOOT_FLAGS_SIZE, "rootfs");
	rootfs = RFS0;
	if(node == 0) {
		db_puts("warning: failed to find rootfs flags!\n");
	}
	else {
		rfs_txt = (char*)node+sizeof(struct jffs2_raw_inode)-4;
		if(!strncmp(rfs_txt, "RFS1", 4)) {
			db_puts("booting RFS1\n");
			rootfs = RFS1;
		} 
#ifdef NFS_SUPPORT
		else if(!strncmp(rfs_txt, "NFS0", 4)) {
			db_puts("booting NFS0\n");
			rootfs = NFS0;
		} 
		else if(!strncmp(rfs_txt, "NFS1", 4)) {
			db_puts("booting NFS1\n");
			rootfs = NFS1;
		} 
#endif /* NFS_SUPPORT */
		else {
			db_puts("booting RFS0\n");
		}
	}

	/* Find the mfcart file */
	mfg_node = jffs2_cat((char *)fs_buffer, BOOT_FLAGS_SIZE, "mfcart");
	if(mfg_node != 0) {
		db_puts("Booting with mfg cartridge layout.\n");
	}

	/* construct the command line */
	if(mfg_node == 0) {
		if(rootfs == RFS0) {
			cmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
			
		} 
		else if(rootfs == RFS1) {
			cmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;
		}
#ifdef NFS_SUPPORT
		else if(rootfs == NFS0) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
			
		} 
		else if(rootfs == NFS1) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;
			
		} 
#endif /* NFS_SUPPORT */
	} else {
		if(rootfs == RFS0) {
			cmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_MFG CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_MFG CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
			
		} 
		else if(rootfs == RFS1) {
			cmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_MFG CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_MFG CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;
		}
#ifdef NFS_SUPPORT
		else if(rootfs == NFS0) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_MFG CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_MFG CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
			
		} 
		else if(rootfs == NFS1) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_MFG CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_MFG CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;
		}
#endif /* NFS_SUPPORT */
	}
	
	if(tfs_load_summary(sum_buffer, kernel_nand_addr)) {
		db_puts("warning: booting alternative kernel!\n");
		if(tfs_load_summary(sum_buffer, alt_kernel_nand_addr)) {
			db_puts("PANIC: unable to load alt summary\n");
			die();
		}
	}

	db_stopwatch_start("LOAD KERNEL");
	image = load_kernel(cmdline);
	db_stopwatch_stop();
	if(image == 0) {
		db_puts("Warning: booting alternative kernel!\n");
		if(tfs_load_summary(sum_buffer, alt_kernel_nand_addr) != 0) {
			die();
		}
		image = load_kernel(altcmdline);
		if(image == 0) {
			db_puts("PANIC: nothing to boot\n");
			die();
		}
	}

#ifdef DISPLAY_SUPPORT
	db_stopwatch_start("SPLASH");
	db_puts("Loading bootsplash\n");
	tfs_load_file("bootsplash.rgb", (u32 *)FRAME_BUFFER_ADDR);
	display_init();
	db_stopwatch_stop();
#endif

	load_cart_id();

	db_puts("Starting the kernel...\n");
	cleanup_for_linux();
	/* jump to image (void, architecture ID, atags pointer) */
	((void(*)(int r0, int r1, unsigned int r2))image)
		(0, MACH_TYPE_LF1000, (unsigned int)params_buffer);

	/* never get here! */
	die();
}
示例#6
0
文件: init.c 项目: hydra/freewpc
/** Initialize the FreeWPC program. */
__noreturn__ void freewpc_init (void)
{
    extern __common__ void system_reset (void);

    /* Initialize the platform specifics first */
    VOIDCALL (platform_init);

    /* Reset the blanking and watchdog circuitry.
     * Eventually, the watchdog will be tickled every 1ms
     * by the IRQ; until interrupts are enabled, we will
     * have to do this periodically ourselves. */
    pinio_watchdog_reset ();

    /* Set init complete flag to false.  When everything is
     * ready, we'll change this to a 1. */
    sys_init_complete = 0;
    periodic_ok = 0;
    sys_init_pending_tasks = 0;

    /* Initialize all of the other kernel subsystems,
     * starting with the hardware-centric ones and moving on
     * to software features. */

    /* Initialize the real-time scheduler.  The periodic functions
    are scheduled at compile-time  using the 'gensched' utility. */
    VOIDCALL (tick_init);

    /* Initialize the hardware.
     * After each init call, tickle the watchdog (IRQ isn't enabled yet)
     * to prevent it from expiring and resetting the CPU.
     * We don't use a callset here because there are some ordering
     * dependencies -- some modules must be initialized before others --
     * and gencallset doesn't allow us to express those conditions.
     */
#ifdef DEBUGGER
    db_init ();
    bpt_init ();
    pinio_watchdog_reset ();
#endif
    ac_init ();
    pinio_watchdog_reset ();
    sol_init ();
    pinio_watchdog_reset ();
#ifdef CONFIG_GI
    gi_init ();
    pinio_watchdog_reset ();
#endif
    display_init ();
    pinio_watchdog_reset ();
    switch_init ();
    pinio_watchdog_reset ();
    flipper_init ();
    pinio_watchdog_reset ();
    lamp_init ();
    pinio_watchdog_reset ();
    device_init ();
    pinio_watchdog_reset ();
    free_timer_init ();
    pinio_watchdog_reset ();
    sound_init ();
    pinio_watchdog_reset ();
#if (MACHINE_PIC == 1)
    pic_init ();
    pinio_watchdog_reset ();
#endif

    /* task_init is somewhat special in that it transforms the system
     * from a single task into a multitasking one.  After this, tasks
     * can be spawned if need be.  A task is created for the current
     * thread of execution, too. */
    task_init ();
    pinio_watchdog_reset ();

#ifdef CONFIG_NATIVE
    /* Notify the simulator when the core OS is up and running. */
    sim_init ();
#endif

    /* Initialize the sound board early in a background
     * thread, since it involves polling for data back from it,
     * which may take unknown (or even infinite) time. */
    sys_init_pending_tasks++;
    task_create_gid (GID_SOUND_INIT, sound_board_init);

    /* Enable interrupts (IRQs and FIRQs).  Do this as soon as possible,
     * but not before all of the hardware modules are done. */
    enable_interrupts ();

    /* Initialize everything else.  Some of these are given explicitly
    to force a particular order, since callsets do not guarantee the
    order of invocation.  For most things the order doesn't matter. */
    deff_init ();
    leff_init ();
    test_init ();
    adj_init ();
    log_init ();
    callset_invoke (init);

    /* Check all adjustments and make sure that their checksums are valid.
    If problems are found, those adjustments will be made sane again. */
    csum_area_check_all ();

    /* Enable periodic processing. */
    periodic_ok = 1;
    task_sleep (TIME_16MS);

    /* The system is initialized from a hardware perspective.
     * Now, perform additional final initializations. */
    system_reset ();

    /* The system can run itself now, this task is done! */
    task_exit ();
}
示例#7
0
void StartThreads( void )
{
    pthread_mutex_t     spinLockMutex;
    pid_t               childPid;
    struct sigaction    sa;
    sigset_t            sigmsk;
    size_t              len;
    ThreadCallback_t    callbacks;

    GlobalAbort = FALSE;

#ifndef __CYGWIN__
    len = confstr( _CS_GNU_LIBPTHREAD_VERSION, NULL, 0 );
    if( len ) {
        pthreadsVersion = CREATEN(char, len);
        confstr( _CS_GNU_LIBPTHREAD_VERSION, pthreadsVersion, len );
    }
#else
    (void)len;
    pthreadsVersion = memstrlink( "Cygwin" );
#endif

    if( !pthreadsVersion || strstr( pthreadsVersion, "linuxthreads" ) ) {
        fprintf( stderr, "havokmud requires NPTL to operate correctly.\n\n"
                         "The signal handling in linuxthreads is just too "
                         "broken to use.\n\n" );
        exit( 1 );
    }

    /* Do we need to detach? */
    if( Daemon ) {
        childPid = fork();
        if( childPid < 0 ) {
            perror( "Couldn't detach in daemon mode" );
            _exit( 1 );
        }

        if( childPid != 0 ) {
            /* This is still the parent, report the child's pid and exit */
            printf( "[Detached as PID %d]\n", childPid );
            /* And exit the parent */
            _exit( 0 );
        }

        /* After this is in the detached child */

        /* Close stdin, stdout, stderr to release the tty */
        close(0);
        close(1);
        close(2);
    }

    LoggingQ      = QueueCreate( 1024 );
    ConnectInputQ = QueueCreate( 256 );
    ConnectDnsQ   = QueueCreate( 64 );
    InputLoginQ   = QueueCreate( 256 );
    InputEditorQ  = QueueCreate( 256 );
    InputPlayerQ  = QueueCreate( 256 );
    InputImmortQ  = QueueCreate( 256 );
    MailQ         = QueueCreate( 128 );
    QueryQ        = QueueCreate( 1024 );
    ProtobufQ     = QueueCreate( 1024 );

    mainThreadId = pthread_self();
    /* 
     * Setup the sigmasks for this thread (which is the parent to all others).
     * This will propogate to all children.
     */
    sigfillset( &sigmsk );
    sigdelset( &sigmsk, SIGUSR1 );
    sigdelset( &sigmsk, SIGUSR2 );
    sigdelset( &sigmsk, SIGHUP );
    sigdelset( &sigmsk, SIGWINCH );
    sigdelset( &sigmsk, SIGINT );
    sigdelset( &sigmsk, SIGSEGV );
    sigdelset( &sigmsk, SIGILL );
    sigdelset( &sigmsk, SIGFPE );
    pthread_sigmask( SIG_SETMASK, &sigmsk, NULL );

    memset( &callbacks, 0, sizeof(ThreadCallback_t) );
    callbacks.sighupFunc = mainSighup;
    thread_register( &mainThreadId, "MainThread", NULL );

    /* Setup signal handler for SIGUSR1 (toggles Debug) */
    sa.sa_sigaction = (sigAction_t)logging_toggle_debug;
    sigemptyset( &sa.sa_mask );
    sa.sa_flags = SA_RESTART;
    sigaction( SIGUSR1, &sa, NULL );

    /* Setup the exit handler */
    atexit( MainDelayExit );

    /* Setup signal handler for SIGINT (shut down cleanly) */
    sa.sa_sigaction = (sigAction_t)signal_interrupt;
    sigemptyset( &sa.sa_mask );
    sa.sa_flags = SA_RESTART;
    sigaction( SIGINT, &sa, NULL );
    
    /* Setup signal handlers that are to be propogated to all threads */
    sa.sa_sigaction = (sigAction_t)signal_everyone;
    sigemptyset( &sa.sa_mask );
    sa.sa_flags = SA_RESTART | SA_SIGINFO;
    sigaction( SIGUSR2, &sa, NULL );
    sigaction( SIGHUP, &sa, NULL );
    sigaction( SIGWINCH, &sa, NULL );

    /* Setup signal handlers for SEGV, ILL, FPE */
    sa.sa_sigaction = (sigAction_t)signal_death;
    sigemptyset( &sa.sa_mask );
    sa.sa_flags = SA_RESTART | SA_SIGINFO;
    sigaction( SIGSEGV, &sa, NULL );
    sigaction( SIGILL, &sa, NULL );
    sigaction( SIGFPE, &sa, NULL );

    versionAdd( "pthreads", pthreadsVersion );
    versionAdd( "TERM", getenv("TERM") );

    thread_create( &loggingThreadId, LoggingThread, NULL, "LoggingThread", 
                   NULL );

#if 0
    curses_start();
    cursesMenuItemAdd( 2, MENU_SYSTEM, "About", mainAbout, NULL );
    cursesMenuItemAdd( 2, MENU_SYSTEM, "Licensing", mainLicensing, NULL );
    cursesMenuItemAdd( 2, MENU_SYSTEM, "Versions", mainVersions, NULL );
    cursesMenuItemAdd( 2, MENU_SYSTEM, "Reload All", mainReloadAll, NULL );
#endif

    LogBanner();

    db_init();
    db_mysql_init();

    memset( &callbacks, 0, sizeof(ThreadCallback_t) );
    callbacks.sigusr2Func = memoryStats;
    thread_create( &memoryThreadId, MemoryCoalesceThread, NULL, 
                   "MemoryCoalesceThread", &callbacks );
    thread_create( &dnsThreadId, DnsThread, NULL, "DnsThread", NULL );
    thread_create( &inputThreadId, InputThread, NULL, "InputThread", NULL );
    thread_create( &loginThreadId, LoginThread, NULL, "LoginThread", NULL );
    thread_create( &editorThreadId, EditorThread, NULL, "EditorThread", NULL );

    mortalPlayingArgs.inputQ = InputPlayerQ;
    thread_create( &mortalPlayingThreadId, PlayingThread, &mortalPlayingArgs,
                   "MortalPlayingThread", NULL );
    
    immortPlayingArgs.inputQ = InputImmortQ;
    thread_create( &immortPlayingThreadId, PlayingThread, &immortPlayingArgs,
                   "ImmortPlayingThread", NULL );

    thread_create( &mysqlThreadId, MysqlThread, NULL, "MySQLThread", NULL );
    thread_create( &protobufThreadId, ProtobufThread, NULL, "ProtobufThread", 
                   NULL );

    pthread_mutex_lock( startupMutex );
    pthread_mutex_unlock( startupMutex );
    db_check_schema_main();

    thread_create( &smtpThreadId, SmtpThread, NULL, "SMTPThread", NULL );

    connectThreadArgs.port = mud_port;
    connectThreadArgs.timeout_sec = 0;
    connectThreadArgs.timeout_usec = 100000;
    thread_create( &connectionThreadId, ConnectionThread, &connectThreadArgs,
                   "ConnectionThread", NULL );

    pthread_mutex_lock( startupMutex );
    pthread_mutex_unlock( startupMutex );

    /* Sit on this and rotate - this causes an intentional deadlock, this
     * thread should stop dead in its tracks
     */
    thread_mutex_init( &spinLockMutex );
    pthread_mutex_lock( &spinLockMutex );
    pthread_mutex_lock( &spinLockMutex );
}
示例#8
0
void *db_worker(void *data)
{
	int id = *((int *) data); /* Whoa... */

	struct transaction_queue_node_t *node;
	struct db_context_t *dbc;
	char code;
	double response_time;
	struct timeval rt0, rt1;
	int local_seed;
	pid_t pid;
	pthread_t tid;
	extern unsigned int seed;
	int status;

	/* Each thread needs to seed in Linux. */
    tid = pthread_self();
    pid = getpid();
	if (seed == -1) {
		struct timeval tv;
		unsigned long junk; /* Purposely used uninitialized */

		local_seed = pid;
		gettimeofday(&tv, NULL);
		local_seed ^=  tid ^ tv.tv_sec ^ tv.tv_usec ^ junk;
	} else {
		local_seed = seed;
	}
	set_random_seed(local_seed);

	/* Open a connection to the database. */
	dbc = db_init();

	if (!exiting && connect_to_db(dbc) != OK) {
		LOG_ERROR_MESSAGE("connect_to_db() error, terminating program");
		printf("cannot connect to database(see details in error.log file, exiting...\n");
		exit(1);
	}

	while (!exiting) {
		/*
		 * I know this loop will prevent the program from exiting
		 * because of the dequeue...
		 */
		node = dequeue_transaction();
		if (node == NULL) {
			LOG_ERROR_MESSAGE("dequeue was null");
			continue;
		}

		/* Execute transaction and record the response time. */
		if (gettimeofday(&rt0, NULL) == -1) {
			perror("gettimeofday");
		}

		status =
			process_transaction(node->client_data.transaction,
								dbc, &node->client_data.transaction_data);
		if (status == ERROR) {
			LOG_ERROR_MESSAGE("process_transaction() error on %s",
							  transaction_name[
								  node->client_data.transaction]);
			/*
			 * Assume this isn't a fatal error, send the results
			 * back, and try processing the next transaction.
			 */
			while (need_reconnect_to_db(dbc))
			{
				LOG_ERROR_MESSAGE("try to reconnect to database");
				disconnect_from_db(dbc);

				if (connect_to_db(dbc) != OK)
				{
					LOG_ERROR_MESSAGE("reconnect to database error, try again after sleep 5 seconds");
					sleep(5);
				}
			}
		}

		if (status == OK) {
			code = 'C';
		} else if (status == STATUS_ROLLBACK) {
			code = 'R';
		} else if (status == ERROR) {
			code = 'E';
		}

		if (gettimeofday(&rt1, NULL) == -1) {
			perror("gettimeofday");
		}

		response_time = difftimeval(rt1, rt0);
		log_transaction_mix(node->client_data.transaction, code, response_time,
							mode_altered > 0 ? node->termworker_id : node->term_id);
		enqueue_terminal(node->termworker_id, node->term_id);

		/* Keep track of how many transactions this thread has done. */
		++worker_count[id];

		/* Keep track of then the last transaction was execute. */
		time(&last_txn[id]);
	}

	/* Disconnect from the database. */
	disconnect_from_db(dbc);

	free(dbc);

	sem_wait(&db_worker_count);

	return NULL;        /* keep compiler quiet */
}
示例#9
0
/**
 * init module function
 */
static int mod_init(void)
{
	load_tm_f load_tm;
#ifdef HAVE_IHTTP
	load_ih_f load_ih;
#endif
	int  i;

	DBG("XJAB:mod_init: initializing ...\n");
	if(!jdomain)
	{
		LOG(L_ERR, "XJAB:mod_init: ERROR jdomain is NULL\n");
		return -1;
	}

	/* import mysql functions */
	if (bind_dbmod())
	{
		LOG(L_ERR, "XJAB:mod_init: error - database module not found\n");
		return -1;
	}
	db_con = (db_con_t**)shm_malloc(nrw*sizeof(db_con_t*));
	if (db_con == NULL)
	{
		LOG(L_ERR, "XJAB:mod_init: Error while allocating db_con's\n");
		return -1;
	}

	/* import the TM auto-loading function */
	if ( !(load_tm=(load_tm_f)find_export("load_tm", NO_SCRIPT, 0))) {
		LOG(L_ERR, "ERROR: xjab:mod_init: can't import load_tm\n");
		return -1;
	}
	/* let the auto-loading function load all TM stuff */
	if (load_tm( &tmb )==-1)
		return -1;

#ifdef HAVE_IHTTP
	/* import the iHTTP auto-loading function */
	if ( !(load_ih=(load_ih_f)find_export("load_ih", IH_NO_SCRIPT_F, 0))) {
		LOG(L_ERR, "ERROR:xjab:mod_init: can't import load_ih\n");
		return -1;
	}
	/* let the auto-loading function load all TM stuff */
	if (load_ih( &ihb )==-1)
		return -1;
#endif
	
	pipes = (int**)pkg_malloc(nrw*sizeof(int*));
	if (pipes == NULL)
	{
		LOG(L_ERR, "XJAB:mod_init:Error while allocating pipes\n");
		return -1;
	}
	
	for(i=0; i<nrw; i++)
	{
		pipes[i] = (int*)pkg_malloc(2*sizeof(int));
		if (!pipes[i])
		{
			LOG(L_ERR, "XJAB:mod_init: Error while allocating pipes\n");
			return -1;
		}
	}
	
	for(i=0; i<nrw; i++)
	{
		db_con[i] = db_init(db_url);
		if (!db_con[i])
		{
			LOG(L_ERR, "XJAB:mod_init: Error while connecting database\n");
			return -1;
		}
		else
		{
			db_use_table(db_con[i], db_table);
			DBG("XJAB:mod_init: Database connection opened successfuly\n");
		}
	}

	
	/** creating the pipees */
	
	for(i=0;i<nrw;i++)
	{
		/* create the pipe*/
		if (pipe(pipes[i])==-1) {
			LOG(L_ERR, "XJAB:mod_init: error - cannot create pipe!\n");
			return -1;
		}
		DBG("XJAB:mod_init: pipe[%d] = <%d>-<%d>\n", i, pipes[i][0],
			pipes[i][1]);
	}
	
	if((jwl = xj_wlist_init(pipes,nrw,max_jobs,cache_time,sleep_time,
				delay_time)) == NULL)
	{
		LOG(L_ERR, "XJAB:mod_init: error initializing workers list\n");
		return -1;
	}
	
	if(xj_wlist_set_aliases(jwl, jaliases, jdomain, proxy) < 0)
	{
		LOG(L_ERR, "XJAB:mod_init: error setting aliases and outbound proxy\n");
		return -1;
	}

	DBG("XJAB:mod_init: initialized ...\n");	
	return 0;
}
示例#10
0
文件: db3.c 项目: crossbuild/rpm
static int db3_dbiOpen(rpmdb rdb, rpmDbiTagVal rpmtag, dbiIndex * dbip, int flags)
{
    const char *dbhome = rpmdbHome(rdb);
    dbiIndex dbi = NULL;
    int rc = 0;
    int retry_open;
    int verifyonly = (flags & RPMDB_FLAG_VERIFYONLY);

    DB * db = NULL;
    DBTYPE dbtype = DB_UNKNOWN;
    uint32_t oflags;
    static int _lockdbfd = 0;

    if (dbip)
	*dbip = NULL;

    if ((dbi = dbiNew(rdb, rpmtag)) == NULL)
	return 1;

    /*
     * Parse db configuration parameters.
     */
    dbConfigure(rpmtag, rdb->db_dbenv == NULL ? &rdb->cfg : NULL, &dbi->cfg);

    /*
     * Map open mode flags onto configured database/environment flags.
     */
    oflags = dbi->cfg.dbi_oflags;
    if ((rdb->db_mode & O_ACCMODE) == O_RDONLY)
	oflags |= DB_RDONLY;

    rc = db_init(rdb, dbhome);

    retry_open = (rc == 0) ? 2 : 0;

    while (retry_open) {
	rc = db_create(&db, rdb->db_dbenv, 0);
	rc = cvtdberr(dbi, "db_create", rc, _debug);

	/* For verify we only want the handle, not an open db */
	if (verifyonly)
	    break;

	if (rc == 0 && db != NULL) {
	    int _printit;
	    char *dbfs = prDbiOpenFlags(oflags, 0);
	    rpmlog(RPMLOG_DEBUG, "opening  db index       %s/%s %s mode=0x%x\n",
		    dbhome, dbi->dbi_file, dbfs, rdb->db_mode);
	    free(dbfs);

	    rc = (db->open)(db, NULL, dbi->dbi_file, NULL,
			    dbtype, oflags, rdb->db_perms);

	    /* Attempt to create if missing, discarding DB_RDONLY (!) */
	    if (rc == ENOENT) {
		oflags |= DB_CREATE;
		oflags &= ~DB_RDONLY;
		dbtype = (rpmtag == RPMDBI_PACKAGES) ?  DB_HASH : DB_BTREE;
		retry_open--;
	    } else {
		retry_open = 0;
	    }

	    /* XXX return rc == errno without printing */
	    _printit = (rc > 0 ? 0 : _debug);
	    rc = cvtdberr(dbi, "db->open", rc, _printit);

	    /* Validate the index type is something we can support */
	    if ((rc == 0) && (dbtype == DB_UNKNOWN)) {
		db->get_type(db, &dbtype);
		if (dbtype != DB_HASH && dbtype != DB_BTREE) {
		    rpmlog(RPMLOG_ERR, _("invalid index type %x on %s/%s\n"),
				dbtype, dbhome, dbi->dbi_file);
		    rc = 1;
		}
	    }

	    if (rc != 0) {
		db->close(db, 0);
		db = NULL;
	    }
	}
    }

    dbi->dbi_db = db;

    dbi->dbi_flags = 0;
    if (oflags & DB_CREATE)
	dbi->dbi_flags |= DBI_CREATED;
    if (oflags & DB_RDONLY)
	dbi->dbi_flags |= DBI_RDONLY;

    if (!verifyonly && rc == 0 && dbi->cfg.dbi_lockdbfd && _lockdbfd++ == 0) {
	rc = dbiFlock(dbi, rdb->db_mode);
    }

    if (rc == 0 && dbi->dbi_db != NULL && dbip != NULL) {
	*dbip = dbi;
    } else {
	(void) dbiClose(dbi, 0);
    }

    return rc;
}
示例#11
0
void generic_worker(void * cvoid, zctx_t * context, void * pipe) {
  workerconfig_t *config = (workerconfig_t*) cvoid;

  rulepackage_t rpkg;
  child_handshake(pipe);


  rpkg.channel = config->channel;
  rpkg.actions = zhash_new();
  rpkg.triggers = zhash_new();
  rpkg.context = context;
  rpkg.base_config = config->base_config;

  // FIX this needs to be initialised differently for each channel
  // normal channels will always have the "value" service,
  // but (for instance) the Camera channel has the "photo" service

  // zhash_t * services = zhash_new();
  
  char * ninja = config->base_config->uuid;
  rpkg.servicename = malloc(strlen(ninja) +
                            strlen(rpkg.channel) + 4);
  sprintf(rpkg.servicename, "n:%s:%s", ninja,rpkg.channel);

  channeldb_t *db = db_init(rpkg.servicename);

  zclock_log("%s worker preparing rules...", rpkg.servicename);

  zclock_log("%s worker reloading rules from db...", rpkg.servicename);
  db_reload_rules(db, &rpkg);

  //  reload_rules_db(context, db, rpkg.servicename, channel, rules, config->base_config);
  zclock_log("%s worker checking rules with server...", rpkg.servicename);
  char * reup = config->base_config->reup_endpoint;
  if(!reup) {
    zclock_log("E: NO REUP CONNECTION DEFINED! Probably dealing with an old server.");
  } else {
    void * reup_sock = zsocket_new(rpkg.context, ZMQ_DEALER);

    zclock_log("connecting to %s", reup);
    zsocket_connect(reup_sock, reup);
    zlist_t * rules = fetch_rules(reup_sock, rpkg.servicename);
    zmsg_t *tmp;
    while(tmp=zlist_pop(rules)) {
      // handle_command(tmp, NULL, &rpkg, db); // FIXME what do we do
                                               // with the reply?
    }
  }

  db_display_rules(db) ;


  zclock_log("%s worker connecting...", rpkg.servicename);
  mdwrk_t *session = mdwrk_new (config->base_config->broker_endpoint, rpkg.servicename, 0);
  zclock_log("%s worker connected!", rpkg.servicename);
  zmsg_t *reply = NULL;
  while (1) {
    zclock_log("%s worker waiting for work.", rpkg.servicename);
    zmsg_t *request = mdwrk_recv (session, &reply);

    if (request == NULL)
      break;              //  Worker was interrupted
    reply = zmsg_new();
    handle_command(request, reply,  &rpkg, db);
  }
  db_destroy(db);
  mdwrk_destroy (&session);
  return;
}
示例#12
0
文件: lispd.c 项目: LISPmob/lispdroid
int main(int argc, char **argv)
{
    int    fd                           = 0;
    pid_t  pid				= 0;	/* child pid */
    pid_t  sid				= 0;

    init();

    /*
     *	set up databases
     */
    if (!db_init()) {
        log_msg(INFO, "Couldn't create databases");
        exit(EXIT_FAILURE);
    }

    /*
     *	Parse command line options
     */
    handle_lispd_command_line(argc, argv);

    /*
     *	see if we need to daemonize, and if so, do it
     */
    if (lispd_config.daemonize) {
        log_msg(INFO, "lispd is backgrounding...");
        if ((pid = fork()) < 0) {
            exit(EXIT_FAILURE);
        }

        if (pid > 0) {
            log_msg(INFO, "done. Running as PID %d", pid);
            exit(EXIT_SUCCESS);
        }
        umask(0);
        if ((sid = setsid()) < 0)
            exit(EXIT_FAILURE);
        if ((chdir("/")) < 0)
            exit(EXIT_FAILURE);

        /*
         * Redirect standard files to /dev/null save fd in
         * case we need to get back to stdout later
         */
        fd = dup(fileno(stdout));
    }

    signal(SIGHUP,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGINT,  signal_handler);
    signal(SIGQUIT, signal_handler);

    init_timers();

    /*
     * Check if lispd is already running. Only allow one instance!
     */
    if (!get_process_lock(getpid())) {
        log_msg(FATAL, "lispd already running, please stop before restarting. If this seems wrong"
                " remove %s.", LISPD_LOCKFILE);


        printf("lispd already running, please stop before restarting.\n If this appears wrong,"
               " remove %s.\n", LISPD_LOCKFILE);
        exit(EXIT_FAILURE);
    }

    if (!setup_netlink()) {
        log_msg(FATAL, "Can't set up netlink socket (is the kernel module loaded?), exiting...");
        die(EXIT_FAILURE);
    }
    if (!setup_rtnetlink()) {
        log_msg(FATAL, "Can't setup rtnetlink socket, exiting...");
        die(EXIT_FAILURE);
    }

    if (!register_lispd_process()) {
        log_msg(FATAL, "Couldn't register lispd process, exiting...");
        die(EXIT_FAILURE);
    }

    log_msg(INFO, "Version %d.%d.%d starting up...",
            MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION);

    /*
     * now build the v4/v6 receive sockets
     */
    if (build_receive_sockets() == 0) {
        log_msg(FATAL, "  exiting...");
        die(EXIT_FAILURE);
    }

    if (build_event_socket() == 0)
    {
        log_msg(FATAL, "  exiting...");
        die(EXIT_FAILURE);
    }
    log_msg(INFO, "Built receive/event sockets");

    /*
     *	Now do the config file
     */
    if (handle_lispd_config_file()) {
        log_msg(FATAL, "Fatal error parsing config file.");
        dump_fatal_error();
        die(EXIT_FAILURE);
    }

    /*
     *	set up syslog now, checking to see if we're daemonizing...
     */
    setup_log();

    log_msg(INFO, "Read config file");

    if (!install_database_mappings()) {
        log_msg(FATAL, "  exiting...");
        die(EXIT_FAILURE);
    }
#ifdef DEADCODE
    if (!install_map_cache_entries())
        log_msg(INFO, "Could not install static map-cache entries");
#endif
    if (!map_register())
        log_msg(INFO, "Could not map register.");

    set_timer(RLOCProbeScan, RLOC_PROBE_CHECK_INTERVAL);

    clear_map_cache();

    listen_on_well_known_port();

    dump_info_file();
    event_loop();
    log_msg(INFO, "exiting...");		/* event_loop returned bad */
    remove_process_lock();
    exit(0);
}
示例#13
0
文件: driver.c 项目: amoalsale/ab
void *terminal_worker(void *data)
{
#ifndef STANDALONE
	int length;
	int sockfd;
#endif /* NOT STANDALONE */

	struct terminal_context_t *tc;
	struct client_transaction_t client_data;
	double threshold;
	int keying_time;
	struct timespec thinking_time, rem;
	int mean_think_time; /* In milliseconds. */
	struct timeval rt0, rt1;
	double response_time;
	extern int errno;
	int rc;
	int local_seed;

#ifdef STANDALONE
	struct db_context_t dbc;
	struct transaction_queue_node_t *node =
			(struct transaction_queue_node_t *)
			malloc(sizeof(struct transaction_queue_node_t));
	extern char sname[32];
	extern int exiting;
#ifdef LIBPQ
	extern char postmaster_port[32];
#endif /* LIBPQ */

#ifdef LIBMYSQL
	extern char dbt2_mysql_port[32];
#endif /* LIBMYSQL */

#endif /* STANDALONE */

	tc = (struct terminal_context_t *) data;
	/* Each thread needs to seed in Linux. */
	if (seed == -1) {
		struct timeval tv;
		unsigned long junk; /* Purposely used uninitialized */

		gettimeofday(&tv, NULL);
		local_seed = getpid() ^ (int) pthread_self() ^ tv.tv_sec ^
				tv.tv_usec ^ junk;
	} else {
		local_seed = seed;
	}
	printf("seed: %u\n", local_seed);
	fflush(stdout);
	srand(local_seed);

#ifdef STANDALONE
#ifdef ODBC
	db_init(sname, DB_USER, DB_PASS);
#endif /* ODBC */
#ifdef LIBPQ
	db_init(DB_NAME, sname, postmaster_port);
#endif /* LIBPQ */
#ifdef LIBMYSQL
	printf("CONNECTED TO DB |%s| |%s| |%s|\n", DB_NAME, sname, dbt2_mysql_port);
	db_init(sname, "", dbt2_mysql_port);
#endif /* LIBMYSQL */

	if (!exiting && connect_to_db(&dbc) != OK) {
		LOG_ERROR_MESSAGE("db_connect() error, terminating program");
		printf("cannot connect to database, exiting...\n");
		exit(1);
	}
#else
	/* Connect to the client program. */
	sockfd = connect_to_client(hostname, client_port);
	if (sockfd < 1) {
		LOG_ERROR_MESSAGE( "connect_to_client() failed, thread exiting...");
		printf("connect_to_client() failed, thread exiting...");
		pthread_exit(NULL);
	}
#endif /* STANDALONE */

	do {
		if (mode_altered == 1) {
			/*
			 * Determine w_id and d_id for the client per
			 * transaction.
			 */
			tc->w_id = w_id_min + get_random(w_id_max - w_id_min + 1);
			tc->d_id = get_random(table_cardinality.districts) + 1;
		}

		/*
		 * Determine which transaction to execute, minimum keying time,
		 * and mean think time.
		 */
		threshold = get_percentage();
		if (threshold < transaction_mix.new_order_threshold) {
			client_data.transaction = NEW_ORDER;
			keying_time = key_time.new_order;
			mean_think_time = think_time.new_order;
		} else if (transaction_mix.payment_actual != 0 &&
			threshold < transaction_mix.payment_threshold) {
			client_data.transaction = PAYMENT;
			keying_time = key_time.payment;
			mean_think_time = think_time.payment;
		} else if (transaction_mix.order_status_actual != 0 &&
			threshold < transaction_mix.order_status_threshold) {
			client_data.transaction = ORDER_STATUS;
			keying_time = key_time.order_status;
			mean_think_time = think_time.order_status;
		} else if (transaction_mix.delivery_actual != 0 &&
			threshold < transaction_mix.delivery_threshold) {
			client_data.transaction = DELIVERY;
			keying_time = key_time.delivery;
			mean_think_time = think_time.delivery;
		} else {
			client_data.transaction = STOCK_LEVEL;
			keying_time = key_time.stock_level;
			mean_think_time = think_time.stock_level;
		}

#ifdef DEBUG
		printf("executing transaction %c\n", 
			transaction_short_name[client_data.transaction]);
		fflush(stdout);
		LOG_ERROR_MESSAGE("executing transaction %c", 
			transaction_short_name[client_data.transaction]);
#endif /* DEBUG */

		/* Generate the input data for the transaction. */
		if (client_data.transaction != STOCK_LEVEL) {
			generate_input_data(client_data.transaction,
					&client_data.transaction_data, tc->w_id);
		} else {
			generate_input_data2(client_data.transaction,
					&client_data.transaction_data, tc->w_id, tc->d_id);
		}

		/* Keying time... */
		pthread_mutex_lock(
				&mutex_terminal_state[KEYING][client_data.transaction]);
		++terminal_state[KEYING][client_data.transaction];
		pthread_mutex_unlock(
				&mutex_terminal_state[KEYING][client_data.transaction]);
		if (time(NULL) < stop_time) {
			sleep(keying_time);
		} else {
			break;
		}
		pthread_mutex_lock(
				&mutex_terminal_state[KEYING][client_data.transaction]);
		--terminal_state[KEYING][client_data.transaction];
		pthread_mutex_unlock(
				&mutex_terminal_state[KEYING][client_data.transaction]);

		/* Note this thread is executing a transation. */
		pthread_mutex_lock(
				&mutex_terminal_state[EXECUTING][client_data.transaction]);
		++terminal_state[EXECUTING][client_data.transaction];
		pthread_mutex_unlock(
				&mutex_terminal_state[EXECUTING][client_data.transaction]);
		/* Execute transaction and record the response time. */
		if (gettimeofday(&rt0, NULL) == -1) {
			perror("gettimeofday");
		}
#ifdef STANDALONE
		memcpy(&node->client_data, &client_data, sizeof(client_data));
/*
		enqueue_transaction(node);
		node = get_node();
		if (node == NULL) {
			LOG_ERROR_MESSAGE("Cannot get a transaction node.\n");
		}
*/
		rc = process_transaction(node->client_data.transaction, &dbc,
				&node->client_data.transaction_data);
		if (rc == ERROR) {
			LOG_ERROR_MESSAGE("process_transaction() error on %s",
					transaction_name[node->client_data.transaction]);
		}
#else /* STANDALONE */
		length = send_transaction_data(sockfd, &client_data);
		length = receive_transaction_data(sockfd, &client_data);
		rc = client_data.status;
#endif /* STANDALONE */
		if (gettimeofday(&rt1, NULL) == -1) {
			perror("gettimeofday");
		}
		response_time = difftimeval(rt1, rt0);
		pthread_mutex_lock(&mutex_mix_log);
		if (rc == OK) {
			fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
					transaction_short_name[client_data.transaction],
					response_time, (int) pthread_self());
		} else if (rc == STATUS_ROLLBACK) {
			fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
					toupper(transaction_short_name[client_data.transaction]),
					response_time, (int) pthread_self());
		} else if (rc == ERROR) {
			fprintf(log_mix, "%d,%c,%f,%d\n", (int) time(NULL),
					'E', response_time, (int) pthread_self());
		}
		fflush(log_mix);
		pthread_mutex_unlock(&mutex_mix_log);
		pthread_mutex_lock(&mutex_terminal_state[EXECUTING][client_data.transaction]);
		--terminal_state[EXECUTING][client_data.transaction];
		pthread_mutex_unlock(&mutex_terminal_state[EXECUTING][client_data.transaction]);

		/* Thinking time... */
		pthread_mutex_lock(&mutex_terminal_state[THINKING][client_data.transaction]);
		++terminal_state[THINKING][client_data.transaction];
		pthread_mutex_unlock(&mutex_terminal_state[THINKING][client_data.transaction]);
		if (time(NULL) < stop_time) {
			thinking_time.tv_nsec = (long) get_think_time(mean_think_time);
			thinking_time.tv_sec = (time_t) (thinking_time.tv_nsec / 1000);
			thinking_time.tv_nsec = (thinking_time.tv_nsec % 1000) * 1000000;
			while (nanosleep(&thinking_time, &rem) == -1) {
				if (errno == EINTR) {
					memcpy(&thinking_time, &rem, sizeof(struct timespec));
				} else {
					LOG_ERROR_MESSAGE(
							"sleep time invalid %d s %ls ns",
							thinking_time.tv_sec,
							thinking_time.tv_nsec);
					break;
				}
			}
		}
		pthread_mutex_lock(&mutex_terminal_state[THINKING][client_data.transaction]);
		--terminal_state[THINKING][client_data.transaction];
		pthread_mutex_unlock(&mutex_terminal_state[THINKING][client_data.transaction]);
	} while (time(NULL) < stop_time);

#ifdef STANDALONE
	/*recycle_node(node);*/
#endif /* STANDALONE */
	/* Note when each thread has exited. */
	pthread_mutex_lock(&mutex_mix_log);
	fprintf(log_mix, "%d,TERMINATED,%d\n", (int) time(NULL),
			(int) pthread_self());
	fflush(log_mix);
	pthread_mutex_unlock(&mutex_mix_log);
	return NULL; /* keep the compiler quiet */
}
示例#14
0
void db_clear_init(void)
{
	flerase(DB_SECTOR);
	db_init();
}
示例#15
0
文件: main.c 项目: jukajunior/Craft
int main(int argc, char **argv) {
    srand(time(NULL));
    rand();
    if (!glfwInit()) {
        return -1;
    }
    create_window();
    if (!window) {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(VSYNC);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetKeyCallback(window, on_key);
    glfwSetMouseButtonCallback(window, on_mouse_button);

    #ifndef __APPLE__
        if (glewInit() != GLEW_OK) {
            return -1;
        }
    #endif

    if (db_init()) {
        return -1;
    }

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LINE_SMOOTH);
    glLogicOp(GL_INVERT);
    glClearColor(0.53, 0.81, 0.92, 1.00);

    GLuint vertex_array;
    glGenVertexArrays(1, &vertex_array);
    glBindVertexArray(vertex_array);

    GLuint texture;
    glGenTextures(1, &texture);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    load_png_texture("texture.png");

    GLuint block_program = load_program(
        "shaders/block_vertex.glsl", "shaders/block_fragment.glsl");
    GLuint matrix_loc = glGetUniformLocation(block_program, "matrix");
    GLuint camera_loc = glGetUniformLocation(block_program, "camera");
    GLuint sampler_loc = glGetUniformLocation(block_program, "sampler");
    GLuint timer_loc = glGetUniformLocation(block_program, "timer");
    GLuint position_loc = glGetAttribLocation(block_program, "position");
    GLuint normal_loc = glGetAttribLocation(block_program, "normal");
    GLuint uv_loc = glGetAttribLocation(block_program, "uv");

    GLuint line_program = load_program(
        "shaders/line_vertex.glsl", "shaders/line_fragment.glsl");
    GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix");
    GLuint line_position_loc = glGetAttribLocation(line_program, "position");

    GLuint item_position_buffer = 0;
    GLuint item_normal_buffer = 0;
    GLuint item_uv_buffer = 0;
    int previous_block_type = 0;

    Chunk chunks[MAX_CHUNKS];
    int chunk_count = 0;

    FPS fps = {0, 0};
    float matrix[16];
    float x = (rand_double() - 0.5) * 10000;
    float z = (rand_double() - 0.5) * 10000;
    float y = 0;
    float dy = 0;
    float rx = 0;
    float ry = 0;
    double px = 0;
    double py = 0;

    int loaded = db_load_state(&x, &y, &z, &rx, &ry);
    ensure_chunks(chunks, &chunk_count,
        floorf(roundf(x) / CHUNK_SIZE),
        floorf(roundf(z) / CHUNK_SIZE), 1);
    if (!loaded) {
        y = highest_block(chunks, chunk_count, x, z) + 2;
    }

    glfwGetCursorPos(window, &px, &py);
    double previous = glfwGetTime();
    while (!glfwWindowShouldClose(window)) {
        update_fps(&fps, SHOW_FPS);
        double now = glfwGetTime();
        double dt = MIN(now - previous, 0.2);
        previous = now;

        if (exclusive && (px || py)) {
            double mx, my;
            glfwGetCursorPos(window, &mx, &my);
            float m = 0.0025;
            rx += (mx - px) * m;
            ry -= (my - py) * m;
            if (rx < 0) {
                rx += RADIANS(360);
            }
            if (rx >= RADIANS(360)){
                rx -= RADIANS(360);
            }
            ry = MAX(ry, -RADIANS(90));
            ry = MIN(ry, RADIANS(90));
            px = mx;
            py = my;
        }
        else {
            glfwGetCursorPos(window, &px, &py);
        }

        if (left_click) {
            left_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (hy > 0 && is_destructable(hw)) {
                set_block(chunks, chunk_count, hx, hy, hz, 0);
            }
        }

        if (right_click) {
            right_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 1, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (is_obstacle(hw)) {
                if (!player_intersects_block(2, x, y, z, hx, hy, hz)) {
                    set_block(chunks, chunk_count, hx, hy, hz, block_type);
                }
            }
        }

        int sz = 0;
        int sx = 0;
        ortho = glfwGetKey(window, 'F');
        fov = glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) ? 15.0 : 65.0;
        if (glfwGetKey(window, 'Q')) break;
        if (glfwGetKey(window, 'W')) sz--;
        if (glfwGetKey(window, 'S')) sz++;
        if (glfwGetKey(window, 'A')) sx--;
        if (glfwGetKey(window, 'D')) sx++;
        if (dy == 0 && glfwGetKey(window, GLFW_KEY_SPACE)) {
            dy = 8;
        }
        float vx, vy, vz;
        get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz);
        if (glfwGetKey(window, 'Z')) {
            vx = -1; vy = 0; vz = 0;
        }
        if (glfwGetKey(window, 'X')) {
            vx = 1; vy = 0; vz = 0;
        }
        if (glfwGetKey(window, 'C')) {
            vx = 0; vy = -1; vz = 0;
        }
        if (glfwGetKey(window, 'V')) {
            vx = 0; vy = 1; vz = 0;
        }
        if (glfwGetKey(window, 'B')) {
            vx = 0; vy = 0; vz = -1;
        }
        if (glfwGetKey(window, 'N')) {
            vx = 0; vy = 0; vz = 1;
        }
        float speed = flying ? 20 : 5;
        int step = 8;
        float ut = dt / step;
        vx = vx * ut * speed;
        vy = vy * ut * speed;
        vz = vz * ut * speed;
        for (int i = 0; i < step; i++) {
            if (flying) {
                dy = 0;
            }
            else {
                dy -= ut * 25;
                dy = MAX(dy, -250);
            }
            x += vx;
            y += vy + dy * ut;
            z += vz;
            if (collide(chunks, chunk_count, 2, &x, &y, &z)) {
                dy = 0;
            }
        }

        int p = floorf(roundf(x) / CHUNK_SIZE);
        int q = floorf(roundf(z) / CHUNK_SIZE);
        ensure_chunks(chunks, &chunk_count, p, q, 0);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        update_matrix_3d(matrix, x, y, z, rx, ry);

        // render chunks
        glUseProgram(block_program);
        glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix);
        glUniform3f(camera_loc, x, y, z);
        glUniform1i(sampler_loc, 0);
        glUniform1f(timer_loc, glfwGetTime());
        for (int i = 0; i < chunk_count; i++) {
            Chunk *chunk = chunks + i;
            if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) {
                continue;
            }
            if (!chunk_visible(chunk, matrix)) {
                continue;
            }
            draw_chunk(chunk, position_loc, normal_loc, uv_loc);
        }

        // render focused block wireframe
        int hx, hy, hz;
        int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz);
        if (is_obstacle(hw)) {
            glUseProgram(line_program);
            glLineWidth(1);
            glEnable(GL_COLOR_LOGIC_OP);
            glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
            GLuint buffer = make_cube_buffer(hx, hy, hz, 0.51);
            draw_lines(buffer, line_position_loc, 3, 48);
            glDeleteBuffers(1, &buffer);
            glDisable(GL_COLOR_LOGIC_OP);
        }

        update_matrix_2d(matrix);

        // render crosshairs
        glUseProgram(line_program);
        glLineWidth(4);
        glEnable(GL_COLOR_LOGIC_OP);
        glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
        GLuint buffer = make_line_buffer();
        draw_lines(buffer, line_position_loc, 2, 4);
        glDeleteBuffers(1, &buffer);
        glDisable(GL_COLOR_LOGIC_OP);

        // render selected item
        update_matrix_item(matrix);
        if (block_type != previous_block_type) {
            previous_block_type = block_type;
            make_single_cube(
                &item_position_buffer, &item_normal_buffer, &item_uv_buffer,
                block_type);
        }
        glUseProgram(block_program);
        glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix);
        glUniform3f(camera_loc, 0, 0, 5);
        glUniform1i(sampler_loc, 0);
        glUniform1f(timer_loc, glfwGetTime());
        glDisable(GL_DEPTH_TEST);
        draw_single_cube(
            item_position_buffer, item_normal_buffer, item_uv_buffer,
            position_loc, normal_loc, uv_loc);
        glEnable(GL_DEPTH_TEST);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    db_save_state(x, y, z, rx, ry);
    db_close();
    glfwTerminate();
    return 0;
}
示例#16
0
/**
 * init module function
 */
static int mod_init(void)
{
	db_res_t* db_res = NULL;
	code_t i, code;
	dc_t* cell; 

		
	DBG("PDT: initializing...\n");
	
	if(hs_two_pow<0)
	{
		LOG(L_ERR, "PDT: mod_init: hash_size_two_pow must be"
					" positive and less than %d\n", MAX_HSIZE_TWO_POW);
		return -1;
	}
	
	if(code_terminator>9 || code_terminator<0)
	{
		LOG(L_ERR, "PDT: mod_init: code_terminator must be a digit\n");
		return -1;
	}

	if(!prefix_valid())
		return -1;

	next_code = (code_t*)shm_malloc(sizeof(code_t));
	if(!next_code)
	{
		LOG(L_ERR, "PDT: mod_init: cannot allocate next_code!\n");
		return -1;
	}
	if(lock_init(&l) == 0)
	{		
		shm_free(next_code);
		LOG(L_ERR, "PDT: mod_init: cannot init the lock\n");
		return -1;	
	}	
	
	if(register_fifo_cmd(get_domainprefix, "get_domainprefix", 0)<0)
	{
		LOG(L_ERR, "PDT: mod_init: cannot register fifo command 'get_domaincode'\n");
		goto error1;
	}	


	/* binding to mysql module */
	if(bind_dbmod())
	{
		LOG(L_ERR, "PDT: mod_init: Database module not found\n");
		goto error1;
	}

	/* open a connection with the database */
	db_con = db_init(db_url);
	if(!db_con)
	{
	
		LOG(L_ERR, "PDT: mod_init: Error while connecting to database\n");        
		goto error1;
	}
	else
	{
		db_use_table(db_con, db_table);
		DBG("PDT: mod_init: Database connection opened successfully\n");
	}
	
	/* init hashes in share memory */
	if( (hash = init_double_hash(hs_two_pow)) == NULL)
	{
		LOG(L_ERR, "PDT: mod_init: hash could not be allocated\n");	
		goto error2;
	}
	
	/* loading all information from database */
	*next_code = 0;
	if(db_query(db_con, NULL, NULL, NULL, NULL, 0, 0, "code", &db_res)==0)
	{
		for(i=0; i<RES_ROW_N(db_res); i++)
		{
			
			code = RES_ROWS(db_res)[i].values[0].val.int_val; 
			if (!code_valid(code))
			{
				LOG(L_ERR, "PDT: mod_init: existing code contains the terminator\n");
				goto error;
			}
			
			if (*next_code < code)
				*next_code = code;

			cell=new_cell(
			(char*)(RES_ROWS(db_res)[i].values[1].val.string_val), code);
			
			if(cell == NULL)
					goto error;
			
			if(add_to_double_hash(hash, cell)<0)
			{
				LOG(L_ERR, "PDT: mod_init: could not add information from database"
								" into shared-memory hashes\n");
				goto error;
			}
			
 		}
		// clear up here
		//print_hash(hash->dhash, hash->hash_size);
		//print_hash(hash->chash, hash->hash_size);

		(*next_code)++;
		if (*next_code < start_range)
				*next_code = start_range;
		*next_code = apply_correction(*next_code);

		DBG("PDT: mod_init: next_code:%d\n", *next_code);
		

		/* free up the space allocated for response */
		if(db_free_query(db_con, db_res)<0)
		{
			LOG(L_ERR, "PDT: mod_init: error when freeing"
				" up the response space\n");
		}
	}
	else
	{
		/* query to database failed */
		LOG(L_ERR, "PDT: mod_init: query to database failed\n");
		goto error;
	}

	db_close(db_con); /* janakj - close the connection */
	/* success code */
	return 0;

error:
	free_double_hash(hash);
error2:
	db_close(db_con);
error1:	
	shm_free(next_code);
	lock_destroy(&l);
	return -1;
}	
示例#17
0
文件: dump.c 项目: the1sky/pytrace
void dump_init(void) {
  reader = reader_malloc(ring);
  buf = malloc(MAX_RECORD_SIZE);
  db_init();
}
示例#18
0
文件: lispd.c 项目: Alphalink/lispmob
int main(int argc, char **argv)
{
    uint32_t            iseed         = 0;  /* initial random number generator */
    pid_t               pid           = 0;    /* child pid */
    pid_t               sid           = 0;


    init_globales();

    /*
     *  Parse command line options
     */

    handle_lispd_command_line(argc, argv);

#ifndef ANDROID
    /*
     *  Check for required capabilities and drop unnecssary privileges
     */

    if(check_capabilities() != GOOD) {
        exit_cleanup();
    }
#else

    /*
     * Check for superuser privileges
     */
    if (geteuid() != 0) {
        lispd_log_msg(LISP_LOG_INFO,"Running %s requires superuser privileges! Exiting...\n", LISPD);
        exit_cleanup();
    }
#endif

    /*
     *  Initialize the random number generator
     */

    iseed = (unsigned int) time (NULL);
    srandom(iseed);

    /*
     * Set up signal handlers
     */
    signal(SIGHUP,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGINT,  signal_handler);
    signal(SIGQUIT, signal_handler);


    /*
     *  set up databases
     */
    if (db_init() != GOOD ||
            map_cache_init() != GOOD ||
            init_referral_cache() != GOOD){
        exit_cleanup();
    }


    /*
     *  see if we need to daemonize, and if so, do it
     */

    if (daemonize) {
        lispd_log_msg(LISP_LOG_DEBUG_1, "Starting the daemonizing process1");
        if ((pid = fork()) < 0) {
            exit_cleanup();
        }
        umask(0);
        if (pid > 0){
            exit(EXIT_SUCCESS);
        }
        if ((sid = setsid()) < 0){
            exit_cleanup();
        }
        if ((chdir("/")) < 0){
            exit_cleanup();
        }
    }



    /*
     *  create timers
     */

    if (build_timers_event_socket(&timers_fd) != GOOD)
    {
        lispd_log_msg(LISP_LOG_CRIT, " Error programing the timer signal. Exiting...");
        exit_cleanup();
    }
    init_timers();



    /*
     * Create net_link socket to receive notifications of changes of RLOC status.
     */
    if ((netlink_fd = opent_netlink_socket()) == -1){
        lispd_log_msg(LISP_LOG_CRIT, " Error programing netlink socket. Exiting...");
        exit_cleanup();
    }

    /*
     *  Parse config file. Format of the file depends on the node: Linux Box or OpenWRT router
     */

#ifdef OPENWRT
    if (config_file == NULL){
        config_file = strdup("/etc/config/lispd");
    }
    err = handle_uci_lispd_config_file(config_file);
#else
    if (config_file == NULL){
        config_file = strdup("/etc/lispd.conf");
    }
    err = handle_lispd_config_file(config_file);
#endif

    if (err != GOOD){
        lispd_log_msg(LISP_LOG_CRIT,"Wrong configuration.");
        exit_cleanup();
    }

    if (ddt_client == FALSE){
        drop_referral_cache();
    }

    if (nat_aware == TRUE){
        nat_set_xTR_ID();
    }
    /*
     * Select the default rlocs for output data packets and output control packets
     */
    set_default_output_ifaces();

    set_default_ctrl_ifaces();

    /*
     * Create tun interface
     */

    if (create_tun(TUN_IFACE_NAME,
            TUN_RECEIVE_SIZE,
            TUN_MTU) != GOOD){
        exit_cleanup();
    }

    /*
     * Assign address to the tun interface and add routing to this interface
     */
    if (configure_routing_to_tun() != GOOD){
        exit_cleanup();
    }

    /*
     * Generate receive sockets for control (4342) and data port (4341)
     */

    if (default_rloc_afi == AF_UNSPEC || default_rloc_afi == AF_INET){
        ipv4_control_input_fd = open_control_input_socket(AF_INET);
        ipv4_data_input_fd = open_data_input_socket(AF_INET);
    }

    if (default_rloc_afi == AF_UNSPEC || default_rloc_afi == AF_INET6){
        ipv6_control_input_fd = open_control_input_socket(AF_INET6);
        ipv6_data_input_fd = open_data_input_socket(AF_INET6);
    }



    /*
     * Request to dump the routing tables to obtain the gatways when processing the netlink messages
     */

    request_route_table(RT_TABLE_MAIN, AF_INET);
    process_netlink_msg(netlink_fd);
    request_route_table(RT_TABLE_MAIN, AF_INET6);
    process_netlink_msg(netlink_fd);


#ifdef OPENWRT
    lispd_log_msg(LISP_LOG_INFO,"LISPmob %s compiled for openWRT\n", LISPD_VERSION);
#else
#ifdef ANDROID
    lispd_log_msg(LISP_LOG_INFO,"LISPmob %s compiled for Android\n", LISPD_VERSION);
#else
    lispd_log_msg(LISP_LOG_INFO,"LISPmob %s compiled for Linux\n", LISPD_VERSION);
#endif
#endif

    lispd_log_msg(LISP_LOG_INFO,"LISPmob (%s): 'lispd' started...", LISPD_VERSION);
    if (router_mode == TRUE){
        lispd_log_msg(LISP_LOG_INFO,"Running as an xTR router");
    }else{
        lispd_log_msg(LISP_LOG_INFO,"Running as a LISP mobile node");
    }



    /*
     *  Register to the Map-Server(s)
     */

    if (nat_aware == TRUE){
        initial_info_request_process();
    }else{
        initial_map_register_process();
        /*
         * SMR proxy-ITRs list to be updated with new mappings
         */

        init_smr(NULL,NULL);
    }


    /*
     * RLOC Probing proxy ETRs
     */
    programming_petr_rloc_probing();


    event_loop();

    lispd_log_msg(LISP_LOG_INFO, "Exiting...");         /* event_loop returned bad */
    closelog();
    return(0);
}
示例#19
0
int main(int argc, char **argv)
{
   char config_file_path[256];
   opt_filename = NULL;
   opt_url = NULL;
   fetch_all = false;
   test_mode = false;
   verbose = false;
   opt_insecure = false;
   used_insecure = false;

   strcpy(config_file_path, "/etc/openrail.conf");
   word usage = false;
   int c;
   while ((c = getopt (argc, argv, ":c:u:f:tpih")) != -1)
      switch (c)
      {
      case 'c':
         strcpy(config_file_path, optarg);
         break;
      case 'u':
         if(!opt_filename) opt_url = optarg;
         break;
      case 'f':
         if(!opt_url) opt_filename = optarg;
         break;
      case 'a':
         fetch_all = true;
         break;
      case 't':
         test_mode = true;
         break;
      case 'p':
         verbose = true;
         break;
      case 'i':
         opt_insecure = true;
         break;
      case 'h':
         usage = true;
         break;
      case ':':
         break;
      case '?':
      default:
         usage = true;
      break;
      }

   char * config_fail;
   if((config_fail = load_config(config_file_path)))
   {
      printf("Failed to read config file \"%s\":  %s\n", config_file_path, config_fail);
      usage = true;
   }

   if(usage) 
   {
      printf("%s %s  Usage: %s [-c /path/to/config/file.conf] [-u <url> | -f <path> | -a] [-t | -r] [-p][-i]\n", NAME, BUILD, argv[0]);
      printf(
             "-c <file>  Path to config file.\n"
             "Data source:\n"
             "default    Fetch latest update.\n"
             "-u <url>   Fetch from specified URL.\n"
             "-f <file>  Use specified file.  (Must already be decompressed.)\n"
             "Actions:\n"
             "default    Apply data to database.\n"
             "-t         Report datestamp on download or file, do not apply to database.\n"
             "Options:\n"
             "-i         Insecure.  Circumvent certificate checks if necessary.\n"
             "-p         Print activity as well as logging.\n"
             );
      exit(1);
   }

   char zs[1024];

   start_time = time(NULL);

   debug = *conf[conf_debug];
  
   _log_init(debug?"/tmp/tscdb.log":"/var/log/garner/tscdb.log", (debug?1:(verbose?4:0)));
   
   _log(GENERAL, "");
   _log(GENERAL, "%s %s", NAME, BUILD);
   
   // Enable core dumps
   struct rlimit limit;
   if(!getrlimit(RLIMIT_CORE, &limit))
   {
      limit.rlim_cur = RLIM_INFINITY;
      setrlimit(RLIMIT_CORE, &limit);
   }
   
   int i;
   for(i = 0; i < MATCHES; i++)
   {
      if(regcomp(&match[i], match_strings[i], REG_ICASE + REG_EXTENDED))
      {
         sprintf(zs, "Failed to compile regex match %d", i);
         _log(MAJOR, zs);
      }
   }
   
   // Initialise database
   if(db_init(conf[conf_db_server], conf[conf_db_user], conf[conf_db_password], conf[conf_db_name])) exit(1);

   {
      word e;
      if((e=database_upgrade(cifdb)))
      {
         _log(CRITICAL, "Error %d in upgrade_database().  Aborting.", e);
         exit(1);
      }
   }

   run = 1;
   tiploc_ignored = false;

   // Zero the stats
   {
      word i;
      for(i = 0; i < MAXStats; i++) { stats[i] = 0; }
   }

   if(fetch_file())
   {
      if(opt_url || opt_filename)
      {
         _log(GENERAL, "Failed to find data.");
         exit(1);
      }
      {
         char report[256];
         _log(GENERAL, "Failed to fetch file.");
         
         sprintf(report, "Failed to collect timetable update after %lld attempts.", stats[Fetches]);
         email_alert(NAME, BUILD, "Timetable Update Failure Report", report);
      }
      exit(1);
   }

   char in_q = 0;
   char b_depth = 0;

   size_t ibuf = 0;
   size_t iobj = 0;
   size_t buf_end;

   // Determine applicable update
   {
      MYSQL_RES * result0;
      MYSQL_ROW row0;
      last_update_id[0] = '\0';
      if(!db_query("SELECT MAX(id) FROM updates_processed"))
      {
         result0 = db_store_result();
         if((row0 = mysql_fetch_row(result0)))
         {
            strcpy(last_update_id, row0[0]);
         }
         mysql_free_result(result0);
      }
   }

   if(last_update_id[0] == '\0')
   {
      _log(CRITICAL, "Failed to determine last update id from database.");
      exit(1);
   }


   if(test_mode)
   {
   }
   else
   {
      char c, pc;
      pc = 0;
      // Run through the file splitting off each JSON object and passing it on for processing.

      // DB may have dropped out due to long delay
      (void) db_connect();
      if(db_start_transaction()) _log(CRITICAL, "Failed to initiate database transaction.");
      while((buf_end = fread(buffer, 1, MAX_BUF, fp_result)) && run && !db_errored)
      {
         for(ibuf = 0; ibuf < buf_end && run && !db_errored; ibuf++)
         {
            c = buffer[ibuf];
            if(c != '\r' && c != '\n') 
            {
               obj[iobj++] = c;
               if(iobj >= MAX_OBJ)
               {
                  _log(CRITICAL, "Object buffer overflow!");
                  exit(1);
               }
               if(c == '"' && pc != '\\') in_q = ! in_q;
               if(!in_q && c == '{') b_depth++;
               if(!in_q && c == '}' && b_depth-- && !b_depth)
               {
                  obj[iobj] = '\0';
                  process_object(obj);
                  iobj = 0;
               }
            }
            pc = c;
         }
      }
      fclose(fp_result);
      if(db_errored)
      {
         _log(CRITICAL, "Update rolled back due to database error.");
         (void) db_rollback_transaction();
      }
      else
      {
         _log(GENERAL, "Committing database updates...");
         if(db_commit_transaction())
         {
            _log(CRITICAL, "Database commit failed.");
         }
         else
         {
            _log(GENERAL, "Committed.");
         }
      }
   }

#define REPORT_SIZE 16384
   char report[REPORT_SIZE];
   report[0] = '\0';

   _log(GENERAL, "");
   _log(GENERAL, "End of run:");

   if(used_insecure)
   {
      strcat(report, "*** Warning: Insecure download used.\n");
      _log(GENERAL, "*** Warning: Insecure download used.");
   }

   sprintf(zs, "             Elapsed time: %ld minutes", (time(NULL) - start_time + 30) / 60);
   _log(GENERAL, zs);
   strcat(report, zs); strcat(report, "\n");
   if(test_mode)
   {
      sprintf(zs, "Test mode.  No database changes made.");
      _log(GENERAL, zs);
      strcat(report, zs); strcat(report, "\n");
      exit(0);
   }

   for(i=0; i<MAXStats; i++)
   {
      sprintf(zs, "%25s: %s", stats_category[i], commas_q(stats[i]));
      if(i == DBError && stats[i]) strcat(zs, " ****************");
      _log(GENERAL, zs);
      strcat(report, zs);
      strcat(report, "\n");
   }

   db_disconnect();

   email_alert(NAME, BUILD, "Timetable Update Report", report);

   exit(0);
}
示例#20
0
文件: lispd.c 项目: Alphalink/lispmob
JNIEXPORT jintArray JNICALL Java_org_lispmob_noroot_LISPmob_1JNI_startLispd
  (JNIEnv *env, jclass cl, jint vpn_tun_fd, jstring storage_path)
{
    jintArray           fd_list;
    jint                sockets_fds[4];
    uint32_t            iseed         = 0;  /* initial random number generator */
    pid_t               pid           = 0;    /* child pid */
    pid_t               sid           = 0;
    char                log_file[1024];
    const char          *path         = NULL;

    memset (log_file,0,sizeof(char)*1024);
    init_globales();

    path = (*env)->GetStringUTFChars(env, storage_path, 0);
    config_file = calloc(1024, sizeof(char));
    strcat(config_file,path);
    strcat(config_file,CONF_FILE_NAME);
    strcat(log_file,path);
    strcat(log_file,LOG_FILE_NAME);
    (*env)->ReleaseStringUTFChars(env, storage_path, path);

    open_log_file(log_file);


    lispd_log_msg(LISP_LOG_INFO,"LISPmob %s compiled for not rooted Android", LISPD_VERSION);



    /*
     *  Initialize the random number generator
     */

    iseed = (unsigned int) time (NULL);
    srandom(iseed);

    /*
     * Set up signal handlers
     */
    signal(SIGHUP,  signal_handler);
    signal(SIGTERM, signal_handler);
    signal(SIGINT,  signal_handler);
    signal(SIGQUIT, signal_handler);

    /*
     *  set up databases
     */
    if (db_init() != GOOD ||
            map_cache_init() != GOOD ||
            init_referral_cache() != GOOD){
        exit_cleanup();
    }

    /*
     *  create timers
     */

    if (build_timers_event_socket(&timers_fd) == 0)
    {
        lispd_log_msg(LISP_LOG_CRIT, " Error programing the timer signal. Exiting...");
        exit_cleanup();
        return (NULL);
    }
    init_timers();

    /*
     * Create net_link socket to receive notifications of changes of RLOC status.
     */
    if ((netlink_fd = opent_netlink_socket()) == -1){
        lispd_log_msg(LISP_LOG_CRIT, " Error programing netlink socket. Exiting...");
        exit_cleanup();
        return (NULL);
    }

    if ((ipc_control_fd    = open_ipc_socket(IPC_CONTROL_RX_PORT)) == -1){
        lispd_log_msg(LISP_LOG_CRIT, " Error programing IPC socket. Exiting...");
        exit_cleanup();
        return (NULL);
    }

    err = handle_lispd_config_file(config_file);


    if (err != GOOD){
        lispd_log_msg(LISP_LOG_CRIT,"Wrong configurationn.");
        ipc_send_log_msg(WRONG_CONF);
        sleep(2);
        exit_cleanup();
        return (NULL);
    }

    if (nat_aware == TRUE){
        nat_set_xTR_ID();
    }

    /*
     * Select the default rlocs for output data packets and output control packets
     */

    set_default_output_ifaces();

    set_default_ctrl_ifaces();

    /*
     * Generate receive sockets for control (4342) and data port (4341)
     */

    if (default_rloc_afi == AF_UNSPEC || default_rloc_afi == AF_INET){
        ipv4_control_input_fd = open_control_input_socket(AF_INET);
        ipv4_data_input_fd = open_data_input_socket(AF_INET);
        if (ipv4_control_input_fd == -1 || ipv4_data_input_fd == -1){
            lispd_log_msg(LISP_LOG_CRIT, " Error programing IPv4 sockets. Exiting...");
            exit_cleanup();
            return (NULL);
        }
    }
    if (default_rloc_afi == AF_UNSPEC || default_rloc_afi == AF_INET6){
        ipv6_control_input_fd = open_control_input_socket(AF_INET6);
        ipv6_data_input_fd = open_data_input_socket(AF_INET6);
        if (ipv6_control_input_fd == -1 || ipv6_data_input_fd == -1){
            lispd_log_msg(LISP_LOG_CRIT, " Error programing IPv6 sockets. Exiting...");
            exit_cleanup();
            return (NULL);
        }
    }

    tun_fd = vpn_tun_fd;





    lispd_log_msg(LISP_LOG_INFO,"LISPmob (%s): 'lispd' started...", LISPD_VERSION);
    if (router_mode == TRUE){
        lispd_log_msg(LISP_LOG_INFO,"Running as an xTR router");
    }else{
        lispd_log_msg(LISP_LOG_INFO,"Running as a LISP mobile node");
    }


    fd_list = (*env)->NewIntArray(env, 4);
    if (fd_list == NULL) {
        return NULL; /* out of memory error thrown */
    }

    if (default_ctrl_iface_v4 != NULL ||  default_ctrl_iface_v6 != NULL){
        sockets_fds[0] = ipv4_control_input_fd;
        sockets_fds[1] = ipv4_data_input_fd;
        sockets_fds[2] = ipv6_control_input_fd;
        sockets_fds[3] = ipv6_data_input_fd;
    }else{ // We started LISPmob without any interface UP */
        ipc_send_log_msg(NO_NETWORK);
        sockets_fds[0] = -1;
        sockets_fds[1] = -1;
        sockets_fds[2] = -1;
        sockets_fds[3] = -1;
    }

    (*env)->SetIntArrayRegion(env, fd_list, 0, 4, sockets_fds);
    return fd_list;
}
示例#21
0
int main(void)
{
    /* initialize a memory-only database */
    fail_unless(db_init(NULL, NULL) == 0);

    /* initialize a share */
    global_share = share_new("/tmp");
    fail_unless(global_share);

    char *cwd = g_get_current_dir();
    fail_unless(share_add(global_share, cwd, TRUE) == 0);
    free(cwd);

    hub_t *hub = hub_new();
    fail_unless(hub);
    hub->me = user_new("nick", NULL, NULL, NULL, NULL, 0ULL, hub);
    fail_unless(hub->me);
    cc_t *cc = cc_new(-1, hub);
    fail_unless(cc);
    fail_unless(cc->state == CC_STATE_MYNICK);

    /* login a test user on the hub */
    user_t *test_user = user_new("foo", NULL, NULL, NULL, NULL, 0ULL, hub);
    g_hash_table_insert(hub->users, strdup(test_user->nick), test_user);

    /* fake remote nick of the client connection */
    cc->nick = strdup("foo");

    /* requesting a non-existent file should fail */
    int rc = cc_upload_prepare(cc, "non-existent-file", 0, 0);
    fail_unless(rc == -1);

    /* a user with same nick as me requesting a file should fail */
    free(cc->nick);
    cc->nick = strdup("nick");
    rc = cc_upload_prepare(cc, "sphubd\\sphubd.c", 0, 0);
    fail_unless(rc == -1);
    cc->nick = strdup("foo");

    /* cc_upload_prepare should set cc->offset correctly after called */
    cc->offset = 4711ULL;
    rc = cc_upload_prepare(cc, "sphubd\\sphubd.c", 0, 0);
    fail_unless(rc == 0);
    fail_unless(cc->offset == 0ULL);
    fail_unless(cc->bytes_to_transfer == cc->filesize);

    guint64 ofs = 17;
    rc = cc_upload_prepare(cc, "sphubd\\sphubd.c", ofs, 0);
    fail_unless(rc == 0);
    fail_unless(cc->offset == ofs);
    fail_unless(cc->bytes_to_transfer == cc->filesize - ofs);

    /* send commands to a file instead of to a hub */
    cc->fd = open("/tmp/client_test.log", O_RDWR|O_CREAT);
    fail_unless(cc->fd != -1);

    /* nothing in the download queue yet */
    fail_unless(cc_request_download(cc) == -1);

    /* ok, so add a file to the download queue */
    rc = queue_add("bar", "share\\bar-file.zip", 4711ULL, "/tmp/client_test_file.zip", "ABCDEFGHIJKLMNOPQRSTUVWXYZ012");
    fail_unless(rc == 0);

    /* wrong nick in the download queue */
    fail_unless(cc_request_download(cc) == -1);

    /* ok, so add two files to the download queue with correct nick */
    rc = queue_add("foo", "share\\foo-file2.zip", 17ULL, "/tmp/client_test_file2.zip", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234");
    fail_unless(rc == 0);
    rc = queue_add("foo", "share\\foo-file.zip", 4711ULL, "/tmp/client_test_file.zip", "ABCDEFGHIJKLMNOPQRSTUVWXYZ012");
    fail_unless(rc == 0);

    fail_unless(cc_request_download(cc) == 0);
    fail_unless(cc->state == CC_STATE_REQUEST);
    /* should download foo-file.zip first, because they're sorted by filename */
    fail_unless(strcmp(cc->current_queue->target_filename, "/tmp/client_test_file.zip") == 0);

    cc->has_adcget = TRUE;
    cc->has_tthf = TRUE;

    cc_start_download(cc);
    fail_unless(cc->state == CC_STATE_BUSY);
    cc_finish_download(cc);
    /* cc_finish_download should request another file directly if there is one
     * in the download queue */
    fail_unless(cc->state == CC_STATE_REQUEST);
    fail_unless(strcmp(cc->current_queue->target_filename, "/tmp/client_test_file2.zip") == 0);

    cc_start_download(cc);
    fail_unless(cc->state == CC_STATE_BUSY);
    cc_finish_download(cc);
    fail_unless(cc->state == CC_STATE_READY);

    /* nothing more in the download queue */
    fail_unless(cc_request_download(cc) == -1);

    /* zero-sized files are not downloaded (except filelists) */
    rc = queue_add("foo", "share\\file3.zip", 0ULL, "/tmp/client_test_file3.zip", "ABCDEFGHIJKLMNOPQRSTUVWXYZ345");
    fail_unless(rc == 0);
    fail_unless(cc_request_download(cc) == -1);

    /* download a filelist */
    cc->has_xmlbzlist = true;
    rc = queue_add_filelist("foo", false);
    fail_unless(rc == 0);
    fail_unless(cc_request_download(cc) == 0);
    fail_unless(strcmp(cc->current_queue->target_filename, "/tmp/files.xml.foo.bz2") == 0);

    cc_start_download(cc);
    fail_unless(cc->state == CC_STATE_BUSY);
    cc_finish_download(cc);
    fail_unless(cc->state == CC_STATE_READY);

    return 0;
}
示例#22
0
int main() {
  int d,m,y;
  char query[1024];
  char *env;
  char *coord=NULL;
  char *search=NULL;
  char buf[1024];
  char *tmp;

  time_t t;
  struct tm *tt;

  time(&t);
  tt = localtime(&t);
  d = tt->tm_mday;
  m = tt->tm_mon+1;
  y = tt->tm_year+1900;

  env = getenv("QUERY_STRING");
  if (env) {
    char *s;
    s = strstr(env, "d="); if (s) sscanf(s, "d=%d", &d);
    s = strstr(env, "m="); if (s) sscanf(s, "m=%d", &m);
    s = strstr(env, "y="); if (s) sscanf(s, "y=%d", &y);
    s = strstr(env, "c="); 
    if (s) s+=2; else { // spatna kompatibilita so znackami
      s = strstr(env, "in=");
      if (s) s+=3;
    }
    if (s) {
      query[0]=0;
      sscanf(s, "%1000[^&]", query);
      coord=StringDecode(query);
    }
    s = strstr(env, "search="); 
    if (s) {
      query[0]=0;
      sscanf(s+7, "%1000[^&]", query);
      search = StringDecode(query);
    }
  }

  if (db_init()<0) return 1;

  printf("Content-Type: text/html; charset=UTF-8\n\n");

  printf("<html><head>\n"
      "<link rel=\"stylesheet\" href=\"breviar.css\">\n");

  Rst(&kontext);
  kontext_last_hb=kontext_last_he=-1;
  first.h=last.h=-1;

  if (coord) {
    printf("<title>%s</title>\n"
      "</head><body>\n"
      "<div class=\"nadpis\">%s</div>\n\n", coord, coord);
    kalendar = 0;
    scan_string(coord);
    yyparse();
    printf("<p>\n"
        "<form action=\"pismo.cgi\" method=\"get\">\n"
        "<input type=\"text\" name=\"c\">\n"
        "<input type=\"submit\" value=\"Zobraz\">\n"
        "</form>\n");
    {
      char *tmp = StringEncode(kontext.buf+1);
      printf(// "<p>\n"
          "<a href=\"pismo.cgi?c=%s\">Kontext</a>", tmp);
      free(tmp);
    }
    printf("&nbsp; &nbsp;");
    if (first.h!=-1) {
      char *b;
      int h;
      get_prev(first.k, first.h, &b, &h);
      if (b!=NULL) {
        snprintf(buf, sizeof(buf), "%s %d", b, h);
        tmp = StringEncode(buf);
        printf(// "<p>\n"
            "<a href=\"pismo.cgi?c=%s\">Dozadu (%s %d)</a>", tmp, b, h);
        free(tmp);
        free(b);
      }
    }
    printf("&nbsp; &nbsp;");
    if (last.h!=-1){
      char *b;
      int h;
      get_next(last.k, last.h, &b, &h);
      if (b!=NULL) {
        snprintf(buf, sizeof(buf), "%s %d", b, h);
        tmp = StringEncode(buf);
        printf(// "<p>\n"
            "<a href=\"pismo.cgi?c=%s\">Dopredu (%s %d)</a>", tmp, b, h);
        free(tmp);
        free(b);
      }
    }
    printf("<p>\n"
        "<form action=\"pismo.cgi\" method=\"get\">\n"
        "<input type=\"text\" name=\"search\">\n"
        "<input type=\"submit\" value=\"Hľadaj\">\n"
        "</form>\n");
  } else if (search) {
    char *b,*t;
    int h,v;

    printf("<title>Vyhľadávanie \"%s\"</title>\n"
        "</head><body>\n"
        "<div class=\"nadpis\">Vyhľadávanie \"%s\"</div>\n\n",
        search, search);

    fulltext_search(search);

    while (get_fulltext_result(&b, &h, &v, &t)) {
      int i,in,var;
      snprintf(buf, sizeof(buf), "%s%d", b,h);
      tmp = StringEncode(buf);
      printf("\n<p> <a href=\"pismo.cgi?c=%s\">%s%d", tmp, b, h);
      if (v!=-1) printf(",%d", v);
      printf("</a>: ");
      free(tmp);
      for (i=in=var=0; t[i]; i++) {
        if (t[i]=='<') {
          in = 1;
          if (!strncmp(t+i+1, "var>", 4)) var = 1;
          if (!strncmp(t+i+1, "/var>", 5)) var = 0;
        }
        if (!in && !var) printf("%c", t[i]);
        if (t[i]=='>') in = 0;
      }
    }

    printf("<p>\n"
        "<form action=\"pismo.cgi\" method=\"get\">\n"
        "<input type=\"text\" name=\"c\">\n"
        "<input type=\"submit\" value=\"Zobraz\">\n"
        "</form>\n");
    printf("<p>\n"
        "<form action=\"pismo.cgi\" method=\"get\">\n"
        "<input type=\"text\" name=\"search\">\n"
        "<input type=\"submit\" value=\"Hľadaj\">\n"
        "</form>\n");
    
    free_fulltext_search();
  } else {
    char *ct;
    if (!get_citania(y,m,d, &zalm, &ct)) return 3;

    kalendar = 1;

    //  printf("%s %s %s %s\n", row[0], row[1], row[2], row[3]);

    printf("<title>Čítania na %d.%d.%d</title>\n"
        "</head><body>\n"
        "<div class=\"nadpis\">Liturgické čítania na %d.%d.%d</div>\n\n",
        d,m,y,d,m,y);
    scan_string(ct);
    yyparse();

    /* toto asi nechceme
    {
      char *tmp = StringEncode(kontext.buf+1);
      printf("<p>\n"
          "<a href=\"pismo.cgi?c=%s\">Kontext</a>", tmp);
      free(tmp);
    }
    */

    free(zalm);
    free(ct);
  }
  printf("</body></html>\n");

  free_scan_string();

  db_close();
  return 0;
}
示例#23
0
文件: main.c 项目: akalend/mymc
int main(int argc, char **argv){

	int mc_sock;
	addr_t mc_addr;	
	ev_io  mc_io;
	sophiadb_t * db;		
	int c;	
	
	
	while (1) {
		int option_index = 0;
		static struct option long_options[] = {
			{"help",		no_argument,		0, 'h'},
			{"version",		no_argument,		0, 'V'},
			{"max-clients",	required_argument,	0, 'l'},
			{0, 0, 0, 0}
		};
		c = getopt_long(argc, argv, "n:Vc:t", long_options, &option_index);
		if (c == -1)
			break;
		switch (c) {
			case 'c':
				confilename = optarg;
				break;
			case 'n':
				max_clients = atoi(optarg);
				break;
			case 'V':
				printf("Version %s\n",  MYMC_VERSION);
				exit(0);
			case 't':
				is_trace = 1;
				break;			default:
				usage(argv[0], c == 'h' ? EXIT_SUCCESS : EXIT_FAILURE);
		}
	}
	

	if (confilename) 
		parse(confilename, &server_ctx);
	else	
		parse( CONFIGFILE, &server_ctx);

	//assert(server_ctx.logfile);
	//assert(server_ctx.listen);
	
	if (!server_ctx.listen) {
		perror("undefined listen port");
		exit(1);
	}
	

	flog =  server_ctx.logfile ? fopen(server_ctx.logfile, "a+") : fopen("error.log", "a+");
	
	if (flog) {		
		time_t lt;
  		lt = time(NULL);
  		fprintf(flog, "server started at %s\n",ctime(&lt));	
	}	else {
			perror("can not create log file");
			exit(1);
		}

	daemonize(server_ctx.is_demonize, server_ctx.pidfile, server_ctx.username);

	set_rlimit();	
	ignore_sigpipe();
		
	init_addr(&mc_addr, server_ctx.listen);

	mc_sock = socket(mc_addr.pf_family, SOCK_STREAM, 0);
	if (mc_sock < 0) {
		perror("can't create socket");
		exit(1);
	}

	listen_sock(mc_sock, &mc_addr);
	
	//TODO	
	if (is_trace)
		printf("pid=%ld\n\n", (long)getpid());
	
	clients = calloc(max_clients, sizeof(fd_ctx));
	if (!clients) {
		perror_fatal("Cannot allocate array for client descriptors!");		
	}

	int i=0;
	while(i < max_clients) {
		if(clients[i].mc) 
			printf("init err %i\n", i);
		i++;
	}
		
	db = db_init(&server_ctx);
	assert(db);
	
	struct ev_loop *loop = ev_default_loop(0);	
	assert(loop);
	
	ev_set_userdata(loop,(void*)db);	
		
	ev_io_init(  &mc_io, memcached_on_connect, mc_sock, EV_READ);		
	ev_io_start(loop, &mc_io);

	struct ev_timer timeout_watcher;	

	ev_init(&timeout_watcher, periodic_watcher);
	timeout_watcher.repeat = TIME_CHECK_INTERVAL;
	ev_timer_again(loop, &timeout_watcher);

	struct ev_signal signal_watcher,signal_watcher2;
	
//	ev_signal_init (&signal_watcher, sigint_cb, SIGINT);
//	ev_signal_start (loop,  &signal_watcher);
	
	ev_signal_init (&signal_watcher, sigint_cb, SIGTERM);
	ev_signal_start (loop,  &signal_watcher);

	ev_signal_init (&signal_watcher2, sighup_cb, SIGHUP);
	ev_signal_start (loop,  &signal_watcher2);
	

	//start server
	time(&stats.uptime);
	gettimeofday(&t_start, NULL);

	// event loop
	ev_loop(loop, 0);
	
	cllear_mc_all();	
	close(mc_sock);	
	
	if (clients) 
		free(clients);
	
	//ev_loop_destroy(loop);
	
	destroy(db);
	
	if (mc_addr.a_addr) free(mc_addr.a_addr);
	
	if (server_ctx.pidfile) {		
		if( unlink(server_ctx.pidfile))
			printf("cannot delete pid file %s %s\n",server_ctx.pidfile, strerror(errno));
	}	

	free_config(); 
	if (flog) {		
		time_t lt;
  		lt = time(NULL);
  		
  		fprintf(flog, "server finis Ok at %s\n",ctime(&lt));
		fclose(flog);	
	}

	return 0;
	 
}
示例#24
0
int main(int argc, char** argv) {
	(void) argc;
	(void) argv;
	int ret;

	// Create a variable with our program directory
#ifndef PROG_ROOT
	char *prog_dir = xmalloc(sizeof(getenv("HOME")) + sizeof(PROG_DIR) + 2);
	prog_dir[0] = '\0';
	prog_dir = strcat(prog_dir, getenv("HOME"));
#else
	char *prog_dir = xmalloc(sizeof(PROG_ROOT) + sizeof(PROG_DIR) + 2);
	prog_dir[0] = '\0';
	prog_dir = strcat(prog_dir, PROG_ROOT);
#endif

	prog_dir = strcat(prog_dir, "/");
	prog_dir = strcat(prog_dir, PROG_DIR);

	// Check program directory and other things. For now only
	// the program directory.
	check_config(prog_dir);

	ret = chdir(prog_dir);
	if(ret) {
		fprintf(stderr, "Error changing dir to %s: %m\n", prog_dir);
		exit(1);
	}

	// Initiate our DB code.
	db_init(DB);

	// Check if database is OK and possibly upgrade it.
	db_check();

	// vbox is the main vertical container.
	GtkWidget  *vbox;

	// hbox is the main horizontal container.
	GtkWidget  *hbox;

	// Elements for our menu
	GtkWidget  *menubar;
	GtkWidget  *filemenu;
	GtkWidget  *file;
	GtkWidget  *mopt_quit;
	GtkWidget  *mopt_add_feed;

	// Button stuff
	GtkWidget *playbtn;
	GtkWidget *listbtn;
	GtkWidget *btnbox;

	// Podcast list
	GtkWidget *casts;

	GtkAccelGroup *accel;

	//GtkWidget *feeds_treeview;

	gtk_init(&argc, &argv);

	// Create main window
	window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	// Set options to our main window
	gtk_window_set_title(GTK_WINDOW(window), "Podfetcher");
	gtk_window_set_default_size(GTK_WINDOW(window), 530, 500);
	gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
	gtk_window_set_icon(GTK_WINDOW(window), 
			create_pixbuf("/usr/share/icons/gnome/16x16/apps"
				"/multimedia-volume-control.png"));

	//Quit GTK on destroy event
	g_signal_connect_swapped(G_OBJECT(window), "destroy", 
			G_CALLBACK(gtk_main_quit), NULL);

	vbox = gtk_vbox_new(FALSE, 0);
	hbox = gtk_hbox_new(FALSE, 0);

	gtk_container_add(GTK_CONTAINER(window), vbox);

	/*
	 * Create menu
	 */
	menubar = gtk_menu_bar_new();
	filemenu = gtk_menu_new();

	file          = gtk_menu_item_new_with_label("File");
	mopt_add_feed = gtk_menu_item_new_with_label("Add feed");
	mopt_quit     = gtk_menu_item_new_with_label("Quit");
	accel         = gtk_accel_group_new();

	// Add the ctrl-q accelerator to the quit button.
	gtk_window_add_accel_group(GTK_WINDOW(window), accel);
	gtk_widget_add_accelerator(mopt_quit, "activate", accel,
			GDK_q, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

	gtk_menu_item_set_submenu(GTK_MENU_ITEM(file),  filemenu);
	gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), mopt_add_feed);
	gtk_menu_shell_append(GTK_MENU_SHELL(filemenu), mopt_quit);
	gtk_menu_shell_append(GTK_MENU_SHELL(menubar),  file);

	gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, FALSE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);

	/*
	 * Create buttons for updating etc.
	 */
	btnbox = gtk_hbutton_box_new();
	playbtn = gtk_button_new_with_label("Play");
	listbtn = gtk_button_new_with_label("Update Feeds");

	casts = gtk_tree_view_new();
	gtk_tree_view_set_enable_search(GTK_TREE_VIEW(casts), TRUE);
	//gtk_tree_view_set_rules_hint(GTK_TREE_VIEW(casts), TRUE);

	setup_feeds_tree_view(casts);

	gtk_container_add(GTK_CONTAINER(btnbox), playbtn);
	gtk_container_add(GTK_CONTAINER(btnbox), listbtn);
	gtk_button_box_set_layout(GTK_BUTTON_BOX(btnbox),GTK_BUTTONBOX_START);
	gtk_box_pack_start(GTK_BOX(hbox), btnbox, TRUE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(vbox), casts, TRUE, TRUE, 0);

	g_signal_connect(G_OBJECT(playbtn), "clicked",
			G_CALLBACK(play_clicked), NULL);

	/*
	g_signal_connect(G_OBJECT(listbtn), "clicked",
			G_CALLBACK(list_clicked), (gpointer) casts);
	*/

	g_signal_connect(G_OBJECT(mopt_quit), "activate",
			G_CALLBACK(gtk_main_quit), NULL);

	g_signal_connect(G_OBJECT(mopt_add_feed), "activate",
			G_CALLBACK(add_feed), NULL);

	run_thread(populate_casts, casts);

	gtk_widget_show_all(window);


	gtk_main();

	free(prog_dir);
	return EXIT_SUCCESS;
}
示例#25
0
int main(int argc, char *argv[])
{
	bool have_conf = false;
	bool have_log = false;
	char buf[32];
	int i, pid, r;
	FILE *pid_file;
	const char *pidfilename = RUNDIR "/atheme.pid";
#ifdef HAVE_GETRLIMIT
	struct rlimit rlim;
#endif
	curr_uplink = NULL;

	mowgli_init();

	/* Prepare gettext */
#ifdef ENABLE_NLS
	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE_NAME, LOCALEDIR);
	textdomain(PACKAGE_NAME);
#endif

	/* change to our local directory */
	if (chdir(PREFIX) < 0)
	{
		perror(PREFIX);
		return 20;
	}

#ifdef HAVE_GETRLIMIT
	/* it appears certian systems *ahem*linux*ahem*
	 * don't dump cores by default, so we do this here.
	 */
	if (!getrlimit(RLIMIT_CORE, &rlim))
	{
		rlim.rlim_cur = rlim.rlim_max;
		setrlimit(RLIMIT_CORE, &rlim);
	}
#endif
	
	/* do command-line options */
	while ((r = getopt(argc, argv, "c:dhrl:np:v")) != -1)
	{
		switch (r)
		{
		  case 'c':
			  config_file = sstrdup(optarg);
			  have_conf = true;
			  break;
		  case 'd':
			  log_force = true;
			  break;
		  case 'h':
			  print_help();
			  exit(EXIT_SUCCESS);
			  break;
		  case 'r':
			  readonly = true;
			  break;
		  case 'l':
			  log_path = sstrdup(optarg);
			  have_log = true;
			  break;
		  case 'n':
			  runflags |= RF_LIVE;
			  break;
		  case 'p':
			  pidfilename = optarg;
			  break;
		  case 'v':
			  print_version();
			  exit(EXIT_SUCCESS);
			  break;
		  default:
			  printf("usage: atheme [-dhnvr] [-c conf] [-l logfile] [-p pidfile]\n");
			  exit(EXIT_SUCCESS);
			  break;
		}
	}

	if (!have_conf)
		config_file = sstrdup(SYSCONFDIR "/atheme.conf");

	if (!have_log)
		log_path = sstrdup(LOGDIR "/atheme.log");

	cold_start = true;

	runflags |= RF_STARTING;

	me.kline_id = 0;
	me.start = time(NULL);
	CURRTIME = me.start;
	srand(arc4random());
	me.execname = argv[0];

	/* set signal handlers */
	init_signal_handlers();

	/* initialize strshare */
	strshare_init();

	/* open log */
	log_open();
	mowgli_log_set_cb(process_mowgli_log);

	slog(LG_INFO, "%s is starting up...", PACKAGE_STRING);

	/* check for pid file */
	if ((pid_file = fopen(pidfilename, "r")))
	{
		if (fgets(buf, 32, pid_file))
		{
			pid = atoi(buf);

			if (!kill(pid, 0))
			{
				fprintf(stderr, "atheme: daemon is already running\n");
				exit(EXIT_FAILURE);
			}
		}

		fclose(pid_file);
	}

#if HAVE_UMASK
	/* file creation mask */
	umask(077);
#endif

        event_init();
        hooks_init();
        init_netio();
        init_socket_queues();
	db_init();

	translation_init();
#ifdef ENABLE_NLS
	language_init();
#endif
	init_nodes();
	init_confprocess();
	init_newconf();
	servtree_init();

	modules_init();
	pcommand_init();

	conf_init();
	if (!conf_parse(config_file))
	{
		slog(LG_ERROR, "Error loading config file %s, aborting",
				config_file);
		exit(EXIT_FAILURE);
	}

	if (config_options.languagefile)
	{
		slog(LG_DEBUG, "Using language: %s", config_options.languagefile);
		if (!conf_parse(config_options.languagefile))
			slog(LG_INFO, "Error loading language file %s, continuing",
					config_options.languagefile);
	}

	authcookie_init();
	common_ctcp_init();

	if (!backend_loaded && authservice_loaded)
	{
		slog(LG_ERROR, "atheme: no backend modules loaded, see your configuration file.");
		exit(EXIT_FAILURE);
	}

	/* we've done the critical startup steps now */
	cold_start = false;

	/* load our db */
	if (db_load)
		db_load();
	else if (backend_loaded)
	{
		slog(LG_ERROR, "atheme: backend module does not provide db_load()!");
		exit(EXIT_FAILURE);
	}
	db_check();

#ifdef HAVE_FORK
	/* fork into the background */
	if (!(runflags & RF_LIVE))
	{
		close(0);
		if (open("/dev/null", O_RDWR) != 0)
		{
			slog(LG_ERROR, "unable to open /dev/null??");
			exit(EXIT_FAILURE);
		}
		if ((i = fork()) < 0)
		{
			slog(LG_ERROR, "can't fork into the background");
			exit(EXIT_FAILURE);
		}

		/* parent */
		else if (i != 0)
		{
			slog(LG_INFO, "pid %d", i);
			slog(LG_INFO, "running in background mode from %s", PREFIX);
			exit(EXIT_SUCCESS);
		}

		/* parent is gone, just us now */
		if (setsid() < 0)
		{
			slog(LG_ERROR, "unable to create new session: %s", strerror(errno));
			exit(EXIT_FAILURE);
		}
		dup2(0, 1);
		dup2(0, 2);
	}
	else
	{
		slog(LG_INFO, "pid %d", getpid());
		slog(LG_INFO, "running in foreground mode from %s", PREFIX);
	}
#else
	slog(LG_INFO, "running in foreground mode from %s", PREFIX);
#endif

#ifdef HAVE_GETPID
	/* write pid */
	if ((pid_file = fopen(pidfilename, "w")))
	{
		fprintf(pid_file, "%d\n", getpid());
		fclose(pid_file);
	}
	else
	{
		fprintf(stderr, "atheme: unable to write pid file\n");
		exit(EXIT_FAILURE);
	}
#endif
	/* no longer starting */
	runflags &= ~RF_STARTING;

	/* we probably have a few open already... */
	me.maxfd = 3;

	/* DB commit interval is configurable */
	if (db_save && !readonly)
		event_add("db_save", db_save, NULL, config_options.commit_interval);

	/* check expires every hour */
	event_add("expire_check", expire_check, NULL, 3600);

	/* check k/x/q line expires every minute */
	event_add("kline_expire", kline_expire, NULL, 60);
	event_add("xline_expire", xline_expire, NULL, 60);
	event_add("qline_expire", qline_expire, NULL, 60);

	/* check authcookie expires every ten minutes */
	event_add("authcookie_expire", authcookie_expire, NULL, 600);

	/* reseed rng a little every five minutes */
	event_add("rng_reseed", rng_reseed, NULL, 293);

	me.connected = false;
	uplink_connect();

	/* main loop */
	io_loop();

	/* we're shutting down */
	hook_call_shutdown();

	if (db_save && !readonly)
		db_save(NULL);

	remove(pidfilename);
	errno = 0;
	if (curr_uplink != NULL && curr_uplink->conn != NULL)
		sendq_flush(curr_uplink->conn);
	connection_close_all();

	me.connected = false;

	/* should we restart? */
	if (runflags & RF_RESTART)
	{
		slog(LG_INFO, "main(): restarting");

#ifdef HAVE_EXECVE
		execv(BINDIR "/atheme-services", argv);
#endif
	}

	slog(LG_INFO, "main(): shutting down");

	log_shutdown();

	return 0;
}
示例#26
0
/*======================================
 *	CORE : MAINROUTINE
 *--------------------------------------*/
int main (int argc, char **argv)
{
	{// initialize program arguments
		char *p1 = SERVER_NAME = argv[0];
		char *p2 = p1;
		while ((p1 = strchr(p2, '/')) != NULL || (p1 = strchr(p2, '\\')) != NULL)
		{
			SERVER_NAME = ++p1;
			p2 = p1;
		}
		arg_c = argc;
		arg_v = argv;
	}

	malloc_init();// needed for Show* in display_title() [FlavioJS]

#ifdef MINICORE // minimalist Core
	display_title();
	usercheck();
	do_init(argc,argv);
	do_final();
#else// not MINICORE
	set_server_type();
	display_title();
	usercheck();

	db_init();
	signals_init();

	timer_init();
	socket_init();
	plugins_init();

	harmony_core_init();

	do_init(argc,argv);
	plugin_event_trigger(EVENT_ATHENA_INIT);

	{// Main runtime cycle
		int next;
		while (runflag != CORE_ST_STOP) {
			next = do_timer(gettick_nocache());
			do_sockets(next);
		}
	}

	harmony_core_final();

	plugin_event_trigger(EVENT_ATHENA_FINAL);
	do_final();

	timer_final();
	plugins_final();
	socket_final();
	db_final();
#endif

	malloc_final();

	return 0;
}
示例#27
0
文件: rated.c 项目: mprovost/rated
/* Main rated */
int main(int argc, char *argv[]) {
    crew_t crew;
    pthread_t sig_thread;
    sigset_t signal_set;
    struct timeval begin_time, end_time;
    unsigned long sleep_time;
    unsigned long poll_time;
    unsigned long long polls;
    unsigned long long last_poll;
    double rate;
    char *conf_file = NULL;
    char *table;
    char errstr[BUFSIZE];
    int ch, i, freed;
    struct timespec ts;

    dfp = stderr;

    /* Check argument count */
    if (argc < 3)
	usage(argv[0]);

    /* Set default environment */
    config_defaults(set);

    /* Parse the command-line. */
    while ((ch = getopt(argc, argv, "c:p:dhmDt:vz")) != EOF)
	switch ((char) ch) {
	case 'c':
	    conf_file = optarg;
	    break;
	case 'd':
	    set->dbon = FALSE;
	    break;
	case 'D':
	    set->daemon = FALSE;
	    break;
	case 'h':
	    usage(argv[0]);
	    break;
	case 'm':
	    set->multiple++;
	    break;
	case 'p':
	    pid_file = optarg;
	    break;
	case 't':
	    target_file = optarg;
	    break;
	case 'v':
	    set->verbose++;
	    break;
	case 'z':
	    set->withzeros = TRUE;
	    break;
	}

    debug(LOW, "rated version %s starting.\n", VERSION);

    if (set->daemon) {
        if (daemon_init() < 0)
            fatal("Could not fork daemon!\n");
        debug(LOW, "Daemon detached\n");
    }

    pthread_mutex_init(&stats.mutex, NULL);

    /* Initialize signal handler */
    sigemptyset(&signal_set);
    sigaddset(&signal_set, SIGHUP);
    sigaddset(&signal_set, SIGUSR1);
    sigaddset(&signal_set, SIGUSR2);
    sigaddset(&signal_set, SIGTERM);
    sigaddset(&signal_set, SIGINT);
    sigaddset(&signal_set, SIGQUIT);
    if (!set->multiple) 
        checkPID(pid_file, set);

    if (pthread_sigmask(SIG_BLOCK, &signal_set, NULL) != 0)
        fatal("pthread_sigmask error\n");

    /* start a thread to catch signals */
    if (pthread_create(&sig_thread, NULL, sig_handler, (void *) &(signal_set)) != 0)
	fatal("pthread_create error\n");

    /* Read configuration file to establish local environment */
    if (conf_file) {
        if ((read_rated_config(conf_file, set)) < 0) 
            fatal("Could not read config file: %s\n", conf_file);
    } else {
        conf_file = malloc(BUFSIZE);
        if (!conf_file) 
            fatal("Fatal malloc error!\n");
        for(i=0;i<CONFIG_PATHS;i++) {
            snprintf(conf_file, BUFSIZE, "%s%s", config_paths[i], DEFAULT_CONF_FILE); 
            if (read_rated_config(conf_file, set) >= 0)
                break;
            if (i == CONFIG_PATHS-1) {
                snprintf(conf_file, BUFSIZE, "%s%s", config_paths[0], DEFAULT_CONF_FILE); 
                if ((write_rated_config(conf_file, set)) < 0) 
                    fatal("Couldn't write config file.\n");
            }
        }
    }

    /* these probably aren't thread safe*/
    init_snmp("rated");
    /* TODO only do this if we're debugging or not daemonised? */
    snmp_enable_stderrlog();
    /* output oids numerically - this is equivalent to -On in the snmp tools */
    netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, NETSNMP_OID_OUTPUT_NUMERIC);

    if (set->dbon) {
        /* load the database driver */
        /* we need a db connection before we parse the targets file so we can check and create tables */
        if (!(db_init(set) && db_connect(set)))
            fatal("** Database error - check configuration.\n");

        /* create our own internal tables */
        table = db_check_and_create_data_table(RATED);
        if (table == NULL)
            fatal("** Database error - couldn't create rated table.\n");
        else
            free(table);
        if (!db_check_and_create_oids_table(OIDS))
            fatal("** Database error - couldn't create oids table.\n");
    }

    /* build list of hosts to be polled */
    head = hash_target_file(target_file);
    if (head == NULL)
        fatal("Error updating target list.");

    if (hosts < set->threads) {
        debug(LOW, "Number of hosts is less than configured number of threads, defaulting to %i.\n", hosts);
        set->threads = hosts;
    }

    debug(LOW, "Initializing threads (%d).\n", set->threads);
    pthread_mutex_init(&(crew.mutex), NULL);
    pthread_cond_init(&(crew.done), NULL);
    pthread_cond_init(&(crew.go), NULL);
    crew.current = NULL;

    debug(HIGH, "Starting threads...");
    crew.running = set->threads;
    for (i = 0; i < set->threads; i++) {
        crew.member[i].index = i;
        crew.member[i].crew = &crew;
        if (pthread_create(&(crew.member[i].thread), NULL, poller, (void *) &(crew.member[i])) != 0)
	    fatal("pthread_create error\n");
	debug(HIGH, " %i", i);
	}
    debug(HIGH, " done\n");

    /* spin waiting for all threads to start up */
    debug(HIGH, "Waiting for thread startup.\n");
    ts.tv_sec = 0;
    ts.tv_nsec = 10000000; /* 10 ms */
    gettimeofday(&begin_time, NULL);
    while (crew.running > 0 ) {
	nanosleep(&ts, NULL);
    }
    gettimeofday(&end_time, NULL);
    debug(HIGH, "Waited %lu milliseconds for thread startup.\n", timediff(end_time, begin_time));

    debug(LOW, "rated ready.\n");

    /* Loop Forever Polling Target List */
    while (1) {
	/* check if we've been signalled */
	if (quitting) {
            debug(LOW, "Quitting: received signal %i.\n", quit_signal);
            if (set->dbon)
                db_disconnect();
            /* one final stat output */
            print_stats(stats, set);
            unlink(pid_file);
            exit(1);
	} else if (waiting) {
            debug(HIGH, "Processing pending SIGHUP.\n");
            /* this just rebuilds the target list
             * so all of the targets will reset to a first poll */
            /* none of the threads should be running at this point so we shouldn't need a lock */
            freed = free_host_list(head);
            debug(HIGH, "Freed %i hosts\n", freed);
            head = hash_target_file(target_file);
            waiting = FALSE;
	}

        last_poll = stats.polls;

	gettimeofday(&begin_time, NULL);

	PT_MUTEX_LOCK(&(crew.mutex));
        crew.current = head;

	debug(LOW, "Queue ready, broadcasting thread go condition.\n");

	PT_COND_BROAD(&(crew.go));
	PT_MUTEX_UNLOCK(&(crew.mutex));

        /*
         * wait for signals from threads finishing
         * we have to use a do loop because when this starts up the running count will be zero
         * so wait at least once until we get a signal that some thread is done before checking for zero
         */
	PT_MUTEX_LOCK(&(crew.mutex));
        do {
            PT_COND_WAIT(&(crew.done), &(crew.mutex));
        } while (crew.running > 0);
	PT_MUTEX_UNLOCK(&(crew.mutex));

        if (quitting_now)
            continue;

	gettimeofday(&end_time, NULL);
	poll_time = timediff(end_time, begin_time);
        polls = stats.polls - last_poll;
        rate = ((double) polls / poll_time) * 1000;
        /* don't underflow */
        if (poll_time < set->interval) {
	    sleep_time = set->interval - poll_time;
        } else {
            sleep_time = 0;
            stats.slow++;
        }

        /* have to call this before we increment the round counter */
        calc_stats(&stats, poll_time);

        stats.round++;
	debug(LOW, "Poll round %d completed %llu getnexts in %lu ms (%.0f/s).\n", stats.round, polls, poll_time, rate);
        /* insert the internal poll data for this round into the rated table */
        if (set->dbon)
            db_insert(RATED, 0, end_time, stats.polls - last_poll, rate);

	if (set->verbose >= LOW) {
            print_stats(stats, set);
        }

        if (sleep_time > 0) {
            sleepy(sleep_time, set);
        } else {
            debug(LOW, "Slow poll, not sleeping\n");
        }
    } /* while(1) */
    exit(0);
}
示例#28
0
static void perform(void)
{
   int rc;
   time_t last_report;

   last_report = time(NULL) / REPORT_INTERVAL;

   // Initialise database
   db_init(conf.db_server, conf.db_user, conf.db_pass, conf.db_name);

   log_message("");
   log_message("");
   log_message("trustdb started.");

   create_database();

   while(run)
   {   
      stats[ConnectAttempt]++;
      _log(GENERAL, "Connecting socket ...");
      rc=stomp_connect("datafeeds.networkrail.co.uk", 61618);
      if(rc)
      {
         sprintf(zs,"Failed to connect.  Error %d %s", rc, report_error(rc));
         _log(CRITICAL, zs);
      }
      else
      {
         _log(GENERAL, "Connected.");
         holdoff = 0;
         {
            strcpy(headers, "CONNECT\n");
            strcat(headers, "login:"******"\npasscode:");
            strcat(headers, conf.nr_pass);
            strcat(headers, "\n");          
            if(debug)
            {
               sprintf(zs, "client-id:%s-trustdb-debug\n", conf.nr_user);
               strcat(headers, zs);
            }
            else
            {
               sprintf(zs, "client-id:%s-trustdb-%s\n", conf.nr_user, abbreviated_host_id());
               strcat(headers, zs);
            }          
            strcat(headers, "heart-beat:0,20000\n");          
            strcat(headers, "\n");
     
            rc = stomp_tx(headers);
         }
         if(rc)
         {
            sprintf(zs,"Failed to transmit CONNECT message.  Error %d %s", rc, report_error(rc));
            _log(CRITICAL, zs);
         }
         else
         {
            _log(GENERAL, "Sent CONNECT message.  Reading response.");
            rc = stomp_rx(headers, sizeof(headers), body, sizeof(body));
            if(rc)
            {
               sprintf(zs,"Failed to receive.  Error %d %s", rc, report_error(rc));
               _log(CRITICAL, zs);
            }
            else
            {
               sprintf(zs, "Response: Body=\"%s\", Headers:", body);
               _log(GENERAL, zs);
               dump_headers();
               {
                  strcpy(headers, "SUBSCRIBE\n");

                  // Headers
                  strcat(headers, "destination:/topic/TRAIN_MVT_ALL_TOC\n");      
                  if(debug)
                  {
                     sprintf(zs, "activemq.subscriptionName:%s-trustdb-debug\n", conf.nr_user);
                     strcat(headers, zs);
                  }
                  else
                  {
                     sprintf(zs, "activemq.subscriptionName:%s-trustdb-%s\n", conf.nr_user, abbreviated_host_id());
                     strcat(headers, zs);
                  }
                  strcat(headers, "id:1\n");      
                  strcat(headers, "ack:client\n");   
                  strcat(headers, "\n");

                  rc = stomp_tx(headers);
               }
               if(rc)
               {
                  sprintf(zs,"Failed to transmit SUBSCRIBE message.  Error %d %s", rc, report_error(rc));
                  _log(CRITICAL, zs);
               }
               else
               {
                  _log(GENERAL, "Sent SUBSCRIBE message.  Waiting for messages ...");

                  int run_receive = 1;
                  while(run && run_receive)
                  {
                     time_t waited = time(NULL);
                     if( waited / REPORT_INTERVAL != last_report)
                     {
                        report_stats();
                        last_report = waited / REPORT_INTERVAL;
                     }
                     rc = stomp_rx(headers, sizeof(headers), body, sizeof(body));
                     run_receive = (rc == 0);
                     if(rc && run)
                     {
                        // Don't report if the error is due to an interrupt
                        sprintf(zs, "Error receiving frame: %d %s", rc, report_error(rc));
                        _log(MAJOR, zs);
                     }
                     
                     if(run_receive)
                     {
                        time_t now = time(NULL);
                        waited = now - waited;
                        if(waited > 1) 
                        {
                           last_idle = now;
                           if(high_load) _log(MINOR, "Ceasing task shedding.");
                           high_load = false;
                        }
                        else
                        {
                           if(!high_load && now - last_idle > 64)
                           {
                              // Enter high load
                              high_load = true;
                              _log(MINOR, "High load detected.  Shedding tasks.");
                           }
                        }
                              
                        if(debug || waited < 2)
                        {
                           sprintf(zs, "Message receive wait time was %ld seconds.", waited);
                           _log(MINOR, zs);
                        }
                        char message_id[256];
                        message_id[0] = '\0';

                        stats[Bytes] += strlen(headers);
                        stats[Bytes] += strlen(body);

                        if(!strstr(headers, "MESSAGE"))
                        {
                           _log(MAJOR, "Frame received is not a MESSAGE:");
                           dump_headers();
                           run_receive = false;
                           stats[NotMessage]++;
                        }
                     
                        // Find message ID
                        char * message_id_header = strstr(headers, "message-id:");
                        if(run_receive)
                        {
                           if(message_id_header)
                           {
                              size_t i = 0;
                              message_id_header += 11;
                              while(*message_id_header != '\n') message_id[i++] = *message_id_header++;
                              message_id[i++] = '\0';
                           }
                           else
                           {
                              _log(MAJOR, "No message ID found:");
                              dump_headers();
                           }
                        }

                        //sprintf(zs, "Message id = \"%s\"", message_id);
                        //_log(GENERAL, zs);
                        
                        // Process the message
                        if(run_receive) process_message(body);

                        // Send ACK
                        if(run_receive && message_id[0])
                        {
                           strcpy(headers, "ACK\n");
                           strcat(headers, "subscription:1\n");
                           strcat(headers, "message-id:");
                           strcat(headers, message_id);
                           strcat(headers, "\n\n");
                           rc = stomp_tx(headers);
                           if(rc)
                           {
                              sprintf(zs,"Failed to transmit ACK message.  Error %d %s", rc, report_error(rc));
                              _log(CRITICAL, zs);
                              run_receive = false;
                           }
                           else
                           {
                              //_log(GENERAL, "Ack sent OK.");
                           }
                           //sprintf(zs, "%d messages, total size %ld bytes.", count, size);
                           //_log(GENERAL, zs);
                        }
                     }
                  } // while(run && run_receive)
               }
            }
         }
      }
      strcpy(headers, "DISCONNECT\n\n");
      rc = stomp_tx(headers);
      if(rc)
      {
         sprintf(zs, "Failed to send DISCONNECT:  Error %d %s", rc, report_error(rc));
         _log(GENERAL, zs);
      }
      else _log(GENERAL, "Sent DISCONNECT.");
      
      _log(GENERAL, "Disconnecting socket ...");
      rc = stomp_disconnect(); 
      if(rc)
      {
         sprintf(zs, "Failed to disconnect:  Error %d %s", rc, report_error(rc));
         _log(GENERAL, zs);
      }
      else _log(GENERAL, "Disconnected.");

      {      
         word i;
         if(holdoff < 128) holdoff += 16;
         else holdoff = 128;
         for(i = 0; i < holdoff && run; i++) sleep(1);
      }
   }  // while(run)

   db_disconnect();

   if(interrupt)
   {
      _log(CRITICAL, "Terminating due to interrupt.");
   }
   report_stats();
}
示例#29
0
文件: db.c 项目: josephg/sharedb
database *db_new() {
  return db_init(malloc(sizeof(database)));
}
示例#30
0
int
main (int argc, char **argv)
{
    const char *pid_file = NULL;
    const char *run_file = NULL;
    const char *url = APTERYX_SERVER;
    bool background = false;
    pthread_mutexattr_t callback_recursive;
    FILE *fp;
    int i;

    /* Parse options */
    while ((i = getopt (argc, argv, "hdmbp:r:l:")) != -1)
    {
        switch (i)
        {
        case 'd':
            apteryx_debug = true;
            background = false;
            break;
        case 'b':
            background = true;
            break;
        case 'p':
            pid_file = optarg;
            break;
        case 'r':
            run_file = optarg;
            break;
        case 'l':
            url = optarg;
            break;
        case 'm':
            g_mem_set_vtable (glib_mem_profiler_table);
            break;
        case '?':
        case 'h':
        default:
            help ();
            return 0;
        }
    }

    /* Handle SIGTERM/SIGINT/SIGPIPE gracefully */
    signal (SIGTERM, (__sighandler_t) termination_handler);
    signal (SIGINT, (__sighandler_t) termination_handler);
    signal (SIGPIPE, SIG_IGN);

    /* Daemonize */
    if (background && fork () != 0)
    {
        /* Parent */
        return 0;
    }

    /* Create pid file */
    if (background && pid_file)
    {
        fp = fopen (pid_file, "w");
        if (!fp)
        {
            ERROR ("Failed to create PID file %s\n", pid_file);
            goto exit;
        }
        fprintf (fp, "%d\n", getpid ());
        fclose (fp);
    }

    /* Initialise the database */
    db_init ();
    /* Initialise callbacks to clients */
    cb_init ();
    /* Configuration Set/Get */
    config_init ();

    /* Create a lock for currently-validating */
    pthread_mutexattr_init (&callback_recursive);
    pthread_mutexattr_settype (&callback_recursive, PTHREAD_MUTEX_RECURSIVE);
    pthread_mutex_init (&validating, &callback_recursive);

    /* Init the RPC for the server instance */
    rpc = rpc_init ((ProtobufCService *)&apteryx_server_service, &apteryx__client__descriptor, RPC_TIMEOUT_US);
    if (rpc == NULL)
    {
        ERROR ("Failed to initialise RPC service\n");
        goto exit;
    }

    /* Create server and process requests */
    if (!rpc_server_bind (rpc, url, url))
    {
        ERROR ("Failed to start rpc service\n");
        goto exit;
    }

    /* Init the RPC for the proxy client */
    proxy_rpc = rpc_init (NULL, &apteryx__server__descriptor, RPC_TIMEOUT_US);
    if (proxy_rpc == NULL)
    {
        ERROR ("Failed to initialise proxy RPC service\n");
        goto exit;
    }

    /* Create run file */
    if (run_file)
    {
        fp = fopen (run_file, "w");
        if (!fp)
        {
            ERROR ("Failed to create RUN file %s\n", run_file);
            goto exit;
        }
        fclose (fp);
    }

    /* Loop while running */
    while (running)
    {
        pause ();
    }

exit:
    DEBUG ("Exiting\n");

    /* Cleanup callbacks */
    cb_shutdown ();
    db_shutdown ();
    if (proxy_rpc)
    {
        rpc_shutdown (proxy_rpc);
    }
    if (rpc)
    {
        rpc_server_release (rpc, url);
        rpc_shutdown (rpc);
    }

    /* Remove the pid file */
    if (background && pid_file)
        unlink (pid_file);

    /* Remove the run file */
    if (run_file)
        unlink (run_file);

    /* Memory profiling */
    g_mem_profile ();

    return 0;
}