Пример #1
0
static cid_data_t *do_lookup(switch_memory_pool_t *pool, switch_event_t *event, const char *num, switch_bool_t skipurl, switch_bool_t skipcitystate)
{
	char *number = NULL;
	char *name = NULL;
	char *url_query = NULL;
	cid_data_t *cid = NULL;
	cid_data_t *cidtmp = NULL;
	switch_bool_t save_cache = SWITCH_FALSE;

	cid = switch_core_alloc(pool, sizeof(cid_data_t));
	switch_assert(cid);

	number = string_digitsonly(pool, num);
	switch_event_add_header_string(event, SWITCH_STACK_BOTTOM, "caller_id_number", number);

	/* database always wins */
	if (switch_odbc_available() && globals.odbc_dsn && globals.sql) {
		name = do_db_lookup(pool, event, number, globals.sql);
		if (name) {
			cid->name = name;
			cid->src = "phone_database";
			goto done;
		}
	}

	if (globals.cache) {
		cidtmp = check_cache(pool, number);
		if (cidtmp) {
			cid = cidtmp;
			cid->src = switch_core_sprintf(pool, "%s (cache)", cid->src);
			goto done;
		}
	}

	if (!skipurl && globals.whitepages_apikey) {
		cid = do_whitepages_lookup(pool, event, number);
		if (cid && cid->name) {	/* only cache if we have a name */
			save_cache = SWITCH_TRUE;
			goto done;
		}
	}

	if (!skipurl && globals.url) {
		url_query = switch_event_expand_headers(event, globals.url);
		do_lookup_url(pool, event, &name, url_query, NULL, NULL, 0);
		if (name) {
			cid->name = name;
			cid->src = "url";

			save_cache = SWITCH_TRUE;
		}
		if (url_query != globals.url) {
			switch_safe_free(url_query);
		}
	}

  done:
	if (!cid) {
		cid = switch_core_alloc(pool, sizeof(cid_data_t));
		switch_assert(cid);
	}
	/* append area if we can */
	if (!cid->area && !skipcitystate && strlen(number) == 11 && number[0] == '1' && switch_odbc_available() && globals.odbc_dsn && globals.citystate_sql) {

		/* yes, this is really area */
		name = do_db_lookup(pool, event, number, globals.citystate_sql);
		if (name) {
			cid->area = name;
			if (cid->src) {
				cid->src = switch_core_sprintf(pool, "%s,%s", cid->src, "npanxx_database");
			} else {
				cid->src = "npanxx_database";
			}
		}
	}

	if (!cid->area) {
		cid->area = "UNKNOWN";
	}
	if (!cid->name) {
		if (skipcitystate) {
			if (strlen(number) == 11 && number[0] == '1') {
				int a, b, c;
				sscanf(number, "1%3d%3d%4d", &a, &b, &c);
				cid->name = switch_core_sprintf(pool, "%03d-%03d-%04d", a, b, c);
			} else {
				cid->name = number;
			}
		} else {
			cid->name = cid->area;
		}
	}
	if (!cid->src) {
		cid->src = "UNKNOWN";
	}

	if (globals.cache && save_cache) {
		set_cache(pool, number, cid);
	}


	switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG10, "cidlookup source: %s\n", cid->src);
	return cid;
}
Пример #2
0
/***********************************************************************//**
 * @brief Load nodes from file
 *
 * @param[in] filename File name.
 *
 * @exception GException::file_function_data
 *            File contains less than 2 nodes
 * @exception GException::file_function_columns
 *            File contains less than 2 columns
 * @exception GException::file_function_value
 *            File contains invalid value
 *
 * The file function is stored as a column separated value table (CSV) in an
 * ASCII file with (at least) 2 columns. The first column specifies the
 * energy in MeV while the second column specifies the intensity at this
 * energy in units of ph/cm2/s/MeV.
 * The node energies and values will be stored both linearly and as log10.
 * The log10 storing requires that node energies and node values are
 * positive. Also, at least 2 nodes and 2 columns are required in the file
 * function.
 ***************************************************************************/
void GModelSpectralFunc::load_nodes(const std::string& filename)
{
    // Clear nodes and values
    m_lin_nodes.clear();
    m_log_nodes.clear();
    m_lin_values.clear();
    m_log_values.clear();

    // Set filename
    m_filename = filename;

    // Load file
    GCsv csv = GCsv(filename);

    // Check if there are at least 2 nodes
    if (csv.nrows() < 2) {
        throw GException::file_function_data(G_LOAD_NODES, filename,
                                             csv.nrows());
    }

    // Check if there are at least 2 columns
    if (csv.ncols() < 2) {
        throw GException::file_function_columns(G_LOAD_NODES, filename,
                                                csv.ncols());
    }

    // Setup nodes
    double last_energy = 0.0;
    for (int i = 0; i < csv.nrows(); ++i) {
    
        // Get log10 of node energy and value. Make sure they are valid.
        double log10energy;
        double log10value;
        if (csv.real(i,0) > 0) {
            log10energy = std::log10(csv.real(i,0));
        }
        else {
            throw GException::file_function_value(G_LOAD_NODES, filename,
                  csv.real(i,0), "Energy value must be positive.");
        }
        if (csv.real(i,1) > 0) {
            log10value = std::log10(csv.real(i,1));
        }
        else {
            throw GException::file_function_value(G_LOAD_NODES, filename,
                  csv.real(i,1), "Intensity value must be positive.");
        }
        
        // Make sure that energies are increasing
        if (csv.real(i,0) <= last_energy) {
            throw GException::file_function_value(G_LOAD_NODES, filename,
                  csv.real(i,0), "Energy values must be monotonically increasing.");
        }
        
        // Append log10 of node energy and value    
        m_lin_nodes.append(csv.real(i,0));
        m_log_nodes.append(log10energy);
        m_lin_values.push_back(csv.real(i,1));
        m_log_values.push_back(log10value);
        
        // Store last energy for monotonically increasing check
        last_energy = csv.real(i,0);
        
    } // endfor: looped over nodes
    
    // Set pre-computation cache
    set_cache();

    // Return
    return;
}
Пример #3
0
Файл: main.c Проект: buaazp/zimg
/**
 * @brief main The entrance of zimg.
 *
 * @param argc Count of args.
 * @param argv Arg list.
 *
 * @return It returns a int to system.
 */
int main(int argc, char **argv) {
    /* Set signal handlers */
    sigset_t sigset;
    sigemptyset(&sigset);
    struct sigaction siginfo = {
        .sa_sigaction = &sighandler,
        .sa_mask = sigset,
        .sa_flags = SA_RESTART,
    };
    sigaction(SIGINT, &siginfo, NULL);
    sigaction(SIGTERM, &siginfo, NULL);

    if (argc < 2) {
        usage(argc, argv);
        return -1;
    }

    settings_init();
    int i;
    for (i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-d") == 0) {
            settings.is_daemon = 1;
        } else {
            conf_file = argv[i];
        }
    }

    if (conf_file == NULL) {
        usage(argc, argv);
        return -1;
    }

    if (is_file(conf_file) == -1) {
        fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
        return -1;
    }

    if (load_conf(conf_file) == -1) {
        fprintf(stderr, "'%s' load failed!\n", conf_file);
        return -1;
    }

    if (bind_check(settings.port) == -1) {
        fprintf(stderr, "Port %d bind failed!\n", settings.port);
        return -1;
    }

    if (settings.is_daemon == 1) {
        if (daemon(1, 1) < 0) {
            fprintf(stderr, "Create daemon failed!\n");
            return -1;
        } else {
            fprintf(stdout, "zimg %s\n", settings.version);
            fprintf(stdout, "Copyright (c) 2013-2014 zimg.buaa.us\n");
            fprintf(stderr, "\n");
        }
    }
    //init the Path zimg need to use.
    //start log module... ./log/zimg.log
    if (mk_dirf(settings.log_name) != 1) {
        fprintf(stderr, "%s log path create failed!\n", settings.log_name);
        return -1;
    }
    log_init();

    if (settings.script_name[0] != '\0') {
        if (is_file(settings.script_name) == -1) {
            fprintf(stderr, "%s open failed!\n", settings.script_name);
            return -1;
        }
        settings.script_on = 1;
    }

    if (is_dir(settings.img_path) != 1) {
        if (mk_dirs(settings.img_path) != 1) {
            LOG_PRINT(LOG_DEBUG, "img_path[%s] Create Failed!", settings.img_path);
            fprintf(stderr, "%s Create Failed!\n", settings.img_path);
            return -1;
        }
    }
    LOG_PRINT(LOG_DEBUG, "Paths Init Finished.");

    if (settings.mode == 2) {
        LOG_PRINT(LOG_DEBUG, "Begin to Test Memcached Connection...");
        memcached_st *beans = memcached_create(NULL);
        char mserver[32];
        snprintf(mserver, 32, "%s:%d", settings.beansdb_ip, settings.beansdb_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);
        servers = memcached_servers_parse(mserver);
        memcached_server_push(beans, servers);
        memcached_server_list_free(servers);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_NO_BLOCK, 1);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1);
        LOG_PRINT(LOG_DEBUG, "beansdb Connection Init Finished.");
        if (set_cache(beans, "zimg", "1") == -1) {
            LOG_PRINT(LOG_DEBUG, "Beansdb[%s] Connect Failed!", mserver);
            fprintf(stderr, "Beansdb[%s] Connect Failed!\n", mserver);
            memcached_free(beans);
            return -1;
        } else {
            LOG_PRINT(LOG_DEBUG, "beansdb connected to: %s", mserver);
        }
        memcached_free(beans);
    } else if (settings.mode == 3) {
        redisContext* c = redisConnect(settings.ssdb_ip, settings.ssdb_port);
        if (c->err) {
            redisFree(c);
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server faile");
            fprintf(stderr, "SSDB[%s:%d] Connect Failed!\n", settings.ssdb_ip, settings.ssdb_port);
            return -1;
        } else {
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server Success");
        }
    }

    //init magickwand
    MagickCoreGenesis((char *) NULL, MagickFalse);
    /*
    ExceptionInfo *exception=AcquireExceptionInfo();
    MagickInfo *jpeg_info = (MagickInfo *)GetMagickInfo("JPEG", exception);
    if(jpeg_info->thread_support != MagickTrue)
        LOG_PRINT(LOG_DEBUG, "thread_support != MagickTrue");
    jpeg_info->thread_support = MagickTrue;
    if(jpeg_info->thread_support != MagickTrue)
        LOG_PRINT(LOG_DEBUG, "thread_support != MagickTrue");
    MagickInfo *jpg_info = (MagickInfo *)GetMagickInfo("JPG", exception);
    jpg_info->thread_support = MagickTrue;
    */

    int result = pthread_key_create(&gLuaStateKey, thread_lua_dtor);
    if (result != 0) {
        LOG_PRINT(LOG_ERROR, "Could not allocate TLS key for lua_State.");
    }

    //begin to start httpd...
    LOG_PRINT(LOG_DEBUG, "Begin to Start Httpd Server...");
    LOG_PRINT(LOG_INFO, "zimg started");
    evbase = event_base_new();
    evhtp_t *htp = evhtp_new(evbase, NULL);

    evhtp_set_cb(htp, "/dump", dump_request_cb, NULL);
    evhtp_set_cb(htp, "/upload", post_request_cb, NULL);
    evhtp_set_cb(htp, "/admin", admin_request_cb, NULL);
    evhtp_set_cb(htp, "/info", info_request_cb, NULL);
    evhtp_set_cb(htp, "/echo", echo_cb, NULL);
    evhtp_set_gencb(htp, get_request_cb, NULL);
#ifndef EVHTP_DISABLE_EVTHR
    evhtp_use_threads(htp, init_thread, settings.num_threads, NULL);
#endif
    evhtp_set_max_keepalive_requests(htp, settings.max_keepalives);
    evhtp_bind_socket(htp, settings.ip, settings.port, settings.backlog);

    event_base_loop(evbase, 0);

    evhtp_unbind_socket(htp);
    //evhtp_free(htp);
    event_base_free(evbase);
    free_headers_conf(settings.headers);
    free_access_conf(settings.up_access);
    free_access_conf(settings.down_access);
    free_access_conf(settings.admin_access);
    free(settings.mp_set);

    return 0;
}
Пример #4
0
Файл: main.c Проект: alemic/zimg
/**
 * @brief main The entrance of zimg.
 *
 * @param argc Count of args.
 * @param argv Arg list.
 *
 * @return It returns a int to system.
 */
int main(int argc, char **argv)
{
    int c;
    _init_path = getcwd(NULL, 0);
    LOG_PRINT(LOG_INFO, "Get init-path: %s", _init_path);

    /* Set signal handlers */
    sigset_t sigset;
    sigemptyset(&sigset);
    struct sigaction siginfo = {
        .sa_handler = sighandler,
        .sa_mask = sigset,
        .sa_flags = SA_RESTART,
    };
    sigaction(SIGINT, &siginfo, NULL);
    sigaction(SIGTERM, &siginfo, NULL);


    settings_init();
    while (-1 != (c = getopt(argc, argv,
                    "p:"
                    "t:"
                    "l"
                    "c"
                    "M:"
                    "m:"
                    "b:"
                    "h"
                    "k:"
                    )))
    {
        switch(c)
        {
            case 'p':
                settings.port = atoi(optarg);
                break;
            case 't':
                settings.num_threads = atoi(optarg);
                if (settings.num_threads <= 0) {
                    fprintf(stderr, "Number of threads must be greater than 0\n");
                    return 1;
                }
                /* There're other problems when you get above 64 threads.
                 * In the future we should portably detect # of cores for the
                 * default.
                 */
                if (settings.num_threads > 64) {
                    fprintf(stderr, "WARNING: Setting a high number of worker"
                            "threads is not recommended.\n"
                            " Set this value to the number of cores in"
                            " your machine or less.\n");
                }
                break;
            case 'l':
                settings.log = true;
                break;
            case 'c':
                settings.cache_on = true;
                break;
            case 'M':
                strcpy(settings.cache_ip, optarg);
                break;
            case 'm':
                settings.cache_port = atoi(optarg);
                break;
            case 'b':
                settings.backlog = atoi(optarg);
                break;
            case 'k':
                settings.max_keepalives = atoll(optarg);
                break;
            case 'h':
                printf("Usage: ./zimg -p port -t thread_num -M memcached_ip -m memcached_port -l[og] -c[ache] -b backlog_num -k max_keepalives -h[elp]\n");
                exit(1);
            default:
                fprintf(stderr, "Illegal argument \"%c\"\n", c);
                return 1;
        }
    }
    //init the Path zimg need to use.
    LOG_PRINT(LOG_INFO, "Begin to Init the Path zimg Using...");
//    if(is_dir(settings.root_path) != 1)
//    {
//        if(mk_dir(settings.root_path) != 1)
//        {
//            LOG_PRINT(LOG_ERROR, "root_path[%s] Create Failed!", settings.root_path);
//            return -1;
//        }
//    }
//
//
    //start log module... ./log/zimg.log
    if(settings.log)
    {
        const char *log_path = "./log";
        if(is_dir(log_path) != 1)
        {
            if(mk_dir(log_path) != 1)
            {
                LOG_PRINT(LOG_ERROR, "log_path[%s] Create Failed!", log_path);
                return -1;
            }
        }
        log_init();
    }

    if(is_dir(settings.img_path) != 1)
    {
        if(mk_dir(settings.img_path) != 1)
        {
            LOG_PRINT(LOG_ERROR, "img_path[%s] Create Failed!", settings.img_path);
            return -1;
        }
    }
    LOG_PRINT(LOG_INFO,"Paths Init Finished.");

   
    //init memcached connection...
    if(settings.cache_on == true)
    {
        LOG_PRINT(LOG_INFO, "Begin to Init Memcached Connection...");
        memcached_st *memc;
        memc= memcached_create(NULL);

        char mserver[32];
        sprintf(mserver, "%s:%d", settings.cache_ip, settings.cache_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);

        memcached_server_push(memc, servers);
        memcached_server_list_free(servers);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
        //使用NO-BLOCK,防止memcache倒掉时挂死          
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_NO_BLOCK, 1); 
        LOG_PRINT(LOG_INFO, "Memcached Connection Init Finished.");
        if(set_cache("zimg", "1") == -1)
        {
            LOG_PRINT(LOG_WARNING, "Memcached[%s] Connect Failed!", mserver);
            settings.cache_on = false;
        }
        else
        {
            LOG_PRINT(LOG_INFO, "memcached connection to: %s", mserver);
            settings.cache_on = true;
        }
        memcached_free(memc);
    }
    else
        LOG_PRINT(LOG_INFO, "Don't use memcached as cache.");
    //init magickwand
    MagickWandGenesis();

    //begin to start httpd...
    LOG_PRINT(LOG_INFO, "Begin to Start Httpd Server...");
    evbase = event_base_new();
    evhtp_t  * htp    = evhtp_new(evbase, NULL);

    evhtp_set_cb(htp, "/dump", dump_request_cb, NULL);
    evhtp_set_cb(htp, "/upload", post_request_cb, NULL);
    //evhtp_set_gencb(htp, echo_cb, NULL);
    evhtp_set_gencb(htp, send_document_cb, NULL);
#ifndef EVHTP_DISABLE_EVTHR
    evhtp_use_threads(htp, NULL, settings.num_threads, NULL);
#endif
    evhtp_set_max_keepalive_requests(htp, settings.max_keepalives);
    evhtp_bind_socket(htp, "0.0.0.0", settings.port, settings.backlog);

    event_base_loop(evbase, 0);

    evhtp_unbind_socket(htp);
    evhtp_free(htp);
    event_base_free(evbase);
    MagickWandTerminus();

    fprintf(stdout, "\nByebye!\n");
    return 0;
}
static void
clear_cache (GtkSourcePixbufHelper *helper)
{
	set_cache (helper, NULL);
}
Пример #6
0
/***********************************************************************//**
 * @brief Read model from XML element
 *
 * @param[in] xml XML element.
 *
 * @exception GException::invalid_value
 *            Model definition requires at least one node.
 *
 * Read the COMPTEL DRB fitting model from an XML element.
 *
 * The model is composed of nodes that define the normalization value as
 * function of Phibar value. The following XML file syntax is expected:
 *
 *     <source name="Background" type="DRBFitting" instrument="COM">
 *       <node>
 *         <parameter name="Phibar"        .../>
 *         <parameter name="Normalization" .../>
 *       </node>
 *       ...
 *       <node>
 *         <parameter name="Phibar"        .../>
 *         <parameter name="Normalization" .../>
 *       </node>
 *     </source>
 ***************************************************************************/
void GCOMModelDRBFitting::read(const GXmlElement& xml)
{
    // Free space for nodes
    m_phibars.clear();
    m_values.clear();

    // Get number of nodes from XML file
    int nodes = xml.elements("node");

    // Throw an error if there are no nodes
    if (nodes < 1) {
        std::string msg = "DRB fitting model requires at least one Phibar "
                          "node. Please correct XML format.";
        throw GException::invalid_value(G_READ, msg);
    }

    // Loop over all nodes
    for (int i = 0; i < nodes; ++i) {

        // Allocate node parameters
        GModelPar phibar;
        GModelPar normalization;
            
        // Get node
        const GXmlElement* node = xml.element("node", i);

        // Read Phibar parameter
        const GXmlElement* par = gammalib::xml_get_par(G_READ, *node, "Phibar");
        phibar.read(*par);

        // Read Normalization parameter
        par = gammalib::xml_get_par(G_READ, *node, "Normalization");
        normalization.read(*par);

        // Set parameter names
        std::string phibar_name        = "Phibar layer "+gammalib::str(i);
        std::string normalization_name = "Scale factor "+gammalib::str(i);

        // Set Phibar attributes
        phibar.name(phibar_name);
        phibar.unit("deg");
        phibar.has_grad(false);

        // Set normalization attributes
        normalization.name(normalization_name);
        normalization.unit("");
        normalization.has_grad(true);

        // Push node parameters on list
        m_phibars.push_back(phibar);
        m_values.push_back(normalization);

    } // endfor: looped over nodes

    // Set model name
    name(xml.attribute("name"));

    // Set instruments
    instruments(xml.attribute("instrument"));

    // Set observation identifiers
    ids(xml.attribute("id"));

    // Check flag if TS value should be computed
    bool tscalc = (xml.attribute("tscalc") == "1") ? true : false;

    // Set flag if TS value should be computed
    this->tscalc(tscalc);

    // Set pointers
    set_pointers();

    // Set evluation cache
    set_cache();

    // Return
    return;
}
Пример #7
0
Файл: newmt.c Проект: kisom/pmon
static int newmt(void)
{
	int i = 0, j = 0;
	unsigned long chunks;
	unsigned long lo, hi;


#if NMOD_FRAMEBUFFER > 0 
	video_cls();
#endif
	if(setjmp(jmpb_mt)&&(returncode==2)){
		ioctl (STDIN, TCSETAF, &sav);
		firsttime = 0;
		v->test = 0;
		v->pass = 0;
		v->msg_line = 0;
		v->ecount = 0;
		v->ecc_ecount = 0;
		autotest=0;
		firsttime=0;
		/* Clear the screen */
#if NMOD_FRAMEBUFFER > 0
		video_cls();
#endif
		return 0;
	}

	ioctl (STDIN, CBREAK, &sav);
	while(1)
	{
		window=0;
		/* If first time, initialize test */
		windows[0].start =LOW_TEST_ADR>>12;
		windows[0].end= HIGH_TEST_ADR>>12;
        
		if(!firsttime){init();firsttime++;}
        
	    bail = 0;

		/* Find the memory areas I am going to test */
		compute_segments(window);

		if (segs == 0) {
			goto skip_window;
		}
		/* Now map in the window... */
		if (map_page(v->map[0].pbase_addr) < 0) {
			goto skip_window;
		}

		/* Update display of memory segments being tested */
		lo = page_of(v->map[0].start);
		hi = page_of(v->map[segs -1].end);
		aprint(LINE_RANGE, COL_MID+9, lo-0x80000);
		cprint(LINE_RANGE, COL_MID+14, " - ");
		aprint(LINE_RANGE, COL_MID+17, hi-0x80000);
		aprint(LINE_RANGE, COL_MID+23, v->selected_pages);
		cprint(LINE_RANGE, COL_MID+28, 
				((ulong)&_start == LOW_TEST_ADR)?"          ":" Relocated");

		/* Now setup the test parameters based on the current test number */
		/* Figure out the next test to run */
		if (v->testsel >= 0) {
			v->test = v->testsel;
		}
		dprint(LINE_TST, COL_MID+6, v->test, 2, 1);
		cprint(LINE_TST, COL_MID+9, tseq[v->test].msg);
		set_cache(tseq[v->test].cache);

		/* Compute the number of SPINSZ memory segments */
		chunks = 0;
		for(i = 0; i < segs; i++) {
			unsigned long len;
			len = v->map[i].end - v->map[i].start;
			chunks += (len + SPINSZ -1)/SPINSZ;
		}
        
		test_ticks = find_ticks_for_test(chunks, v->test);
        nticks = 0;
		v->tptr = 0;
		cprint(1, COL_MID+8, "                                         ");
		switch(tseq[v->test].pat) {
			/* Now do the testing according to the selected pattern */
			case 0:	/* Moving inversions, all ones and zeros */
				p1 = 0;
				p2 = ~p1;
				movinv1(tseq[v->test].iter,p1,p2);
				BAILOUT;

				/* Switch patterns */
				p2 = p1;
				p1 = ~p2;
				movinv1(tseq[v->test].iter,p1,p2);
				BAILOUT;
				break;

			case 1: /* Moving inversions, 8 bit wide walking ones and zeros. */
                p0 = 0x80;
				for (i=0; i<8; i++, p0=p0>>1) {
					p1 = p0 | (p0<<8) | (p0<<16) | (p0<<24);
					p2 = ~p1;
					movinv1(tseq[v->test].iter,p1,p2);
					BAILOUT;

					/* Switch patterns */
					p2 = p1;
					p1 = ~p2;
					movinv1(tseq[v->test].iter,p1,p2);
					BAILOUT
				}
				break;

			case 2: /* Moving inversions, 32 bit shifting pattern, very long */
                {
                    u_int32_t pa = 0;
                    for (i=0, pa=1; pa; pa=pa<<1, i++) {
					    movinv32(tseq[v->test].iter,pa, 1, 0x80000000, 0, i);
					    BAILOUT
                        movinv32(tseq[v->test].iter,~pa, 0xfffffffe,
								0x7fffffff, 1, i);
					    BAILOUT
				    }
                }
				break;

			case 3: /* Modulo X check, all ones and zeros */
                p1=0;
				for (i=0; i<MOD_SZ; i++) {
					p2 = ~p1;
					modtst(i, tseq[v->test].iter, p1, p2);
					BAILOUT

					/* Switch patterns */
					p2 = p1;
					p1 = ~p2;
					modtst(i, tseq[v->test].iter, p1,p2);
					BAILOUT
				}
				break;

			case 4: /* Modulo X check, 8 bit pattern */
                p0 = 0x80;
				for (j=0; j<8; j++, p0=p0>>1) {
					p1 = p0 | (p0<<8) | (p0<<16) | (p0<<24);
					for (i=0; i<MOD_SZ; i++) {
						p2 = ~p1;
						modtst(i, tseq[v->test].iter, p1, p2);
						BAILOUT

						/* Switch patterns */
						p2 = p1;
						p1 = ~p2;
						modtst(i, tseq[v->test].iter, p1, p2);
						BAILOUT
					}
				}
				break;
			case 5: /* Address test, walking ones */
                addr_tst1();
				BAILOUT;
				break;

			case 6: /* Address test, own address */
                addr_tst2();
				BAILOUT;
				break;

			case 7: /* Block move test */
                block_move(tseq[v->test].iter);
				BAILOUT;
				break;
			case 8: /* Bit fade test */
                if (window == 0 ) {
					bit_fade();
				}
				BAILOUT;
				break;
			case 9: /* Random Data Sequence */
                for (i=0; i < tseq[v->test].iter; i++) {
					movinvr();
					BAILOUT;
				}
				break;
			case 10: /* Random Data */
                for (i=0; i < tseq[v->test].iter; i++) {
					p1 = rand();
					p2 = ~p1;
					movinv1(2,p1,p2);
					BAILOUT;
				}
				break;
		}
skip_window:
		if (bail) {
			goto bail_test;
		}
		/* Rever to the default mapping and enable the cache */
		paging_off();
		set_cache(1);
		window++;
		if (window >= sizeof(windows)/sizeof(windows[0])) {
			window = 0;
		}
		/* We finished the test so clear the pattern */
		cprint(LINE_PAT, COL_PAT, "            ");
skip_test:
		v->test++;
bail_test:

		paging_off();
		set_cache(1);
		check_input();
		window = 0;
		cprint(LINE_PAT, COL_PAT-3, "   ");
		/* If this was the last test then we finished a pass */
		if (v->test >= DEFTESTS || v->testsel >= 0) {
			v->pass++;
			dprint(LINE_INFO, COL_PASS, v->pass, 5, 0);
			v->test = 0;
			v->total_ticks = 0;
			v->pptr = 0;
			cprint(0, COL_MID+8,
				"                                         ");
		}
	}
	return 0;
}
Пример #8
0
/**
 * @brief main The entrance of zimg.
 *
 * @param argc Count of args.
 * @param argv Arg list.
 *
 * @return It returns a int to system.
 */
int main(int argc, char **argv)
{
    int i;
    retry_sleep.tv_sec = 0;
    retry_sleep.tv_nsec = RETRY_TIME_WAIT;      //1000 ns = 1 us

    /* Set signal handlers */
    sigset_t sigset;
    sigemptyset(&sigset);
    struct sigaction siginfo = {
        .sa_handler = sighandler,
        .sa_mask = sigset,
        .sa_flags = SA_RESTART,
    };
    sigaction(SIGINT, &siginfo, NULL);
    sigaction(SIGTERM, &siginfo, NULL);

    if(argc < 2)
    {
        usage(argc, argv);
        return -1;
    }

    settings_init();
    const char *conf_file = NULL;
    for(i=1; i<argc; i++)
    {
        if(strcmp(argv[i], "-d") == 0){
            settings.is_daemon = 1;
        }else{
            conf_file = argv[i];
        }
    }

    if(conf_file == NULL)
    {
        usage(argc, argv);
        return -1;
    }

    if(is_file(conf_file) == -1)
    {
        fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
        return -1;
    }

    if(load_conf(conf_file) == -1)
    {
        fprintf(stderr, "'%s' load failed!\n", conf_file);
        return -1;
    }


    if(settings.is_daemon == 1)
    {
        if(daemon(1, 1) < 0)
        {
            fprintf(stderr, "Create daemon failed!\n");
            return -1;
        }
        else
        {
            fprintf(stdout, "zimg %s\n", settings.version);
            fprintf(stdout, "Copyright (c) 2013-2014 zimg.buaa.us\n");
            fprintf(stderr, "\n");
        }
    }
    //init the Path zimg need to use.
    LOG_PRINT(LOG_DEBUG, "Begin to Init the Path zimg Using...");
    //start log module... ./log/zimg.log
    if(settings.log)
    {
        const char *log_path = "./log";
        if(is_dir(log_path) != 1)
        {
            if(mk_dir(log_path) != 1)
            {
                LOG_PRINT(LOG_DEBUG, "log_path[%s] Create Failed!", log_path);
                fprintf(stderr, "log_path[%s] Create Failed!\n", log_path);
                return -1;
            }
        }
        log_init();
    }

    if(is_dir(settings.img_path) != 1)
    {
        if(mk_dir(settings.img_path) != 1)
        {
            LOG_PRINT(LOG_DEBUG, "img_path[%s] Create Failed!", settings.img_path);
            fprintf(stderr, "%s Create Failed!\n", settings.img_path);
            return -1;
        }
    }
    LOG_PRINT(LOG_DEBUG,"Paths Init Finished.");

    if(settings.mode == 2)
    {
        LOG_PRINT(LOG_DEBUG, "Begin to Test Memcached Connection...");
        memcached_st *beans = memcached_create(NULL);
        char mserver[32];
        snprintf(mserver, 32, "%s:%d", settings.beansdb_ip, settings.beansdb_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);
        servers = memcached_servers_parse(mserver);
        memcached_server_push(beans, servers);
        memcached_server_list_free(servers);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_NO_BLOCK, 1); 
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1); 
        LOG_PRINT(LOG_DEBUG, "beansdb Connection Init Finished.");
        if(set_cache(beans, "zimg", "1") == -1)
        {
            LOG_PRINT(LOG_DEBUG, "Beansdb[%s] Connect Failed!", mserver);
            fprintf(stderr, "Beansdb[%s] Connect Failed!\n", mserver);
            memcached_free(beans);
            return -1;
        }
        else
        {
            LOG_PRINT(LOG_DEBUG, "beansdb connected to: %s", mserver);
        }
        memcached_free(beans);
    }
    else if(settings.mode == 3)
    {
        redisContext* c = redisConnect(settings.ssdb_ip, settings.ssdb_port);
        if(c->err)
        {
            redisFree(c);
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server faile");
            fprintf(stderr, "SSDB[%s:%d] Connect Failed!\n", settings.ssdb_ip, settings.ssdb_port);
            return -1;
        }
        else
        {
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server Success");
        }
    }

    //init magickwand
    MagickWandGenesis();

    //begin to start httpd...
    LOG_PRINT(LOG_DEBUG, "Begin to Start Httpd Server...");
    LOG_PRINT(LOG_INFO, "zimg started");
    evbase = event_base_new();
    evhtp_t *htp = evhtp_new(evbase, NULL);

    evhtp_set_cb(htp, "/dump", dump_request_cb, NULL);
    evhtp_set_cb(htp, "/upload", post_request_cb, NULL);
    //evhtp_set_gencb(htp, echo_cb, NULL);
    evhtp_set_gencb(htp, send_document_cb, NULL);
#ifndef EVHTP_DISABLE_EVTHR
    evhtp_use_threads(htp, init_thread, settings.num_threads, NULL);
#endif
    evhtp_set_max_keepalive_requests(htp, settings.max_keepalives);
    evhtp_bind_socket(htp, "0.0.0.0", settings.port, settings.backlog);

    event_base_loop(evbase, 0);

    evhtp_unbind_socket(htp);
    evhtp_free(htp);
    event_base_free(evbase);
    MagickWandTerminus();
    free_access_conf(settings.up_access);
    free_access_conf(settings.down_access);

    fprintf(stdout, "\nByebye!\n");
    return 0;
}
Пример #9
0
/*
 * grow_fork()
 *
 * Try to add enough allocation blocks to 'fork'
 * so that it is 'ablock' allocation blocks long.
 */
static int grow_fork(struct hfs_fork *fork, int ablocks)
{
    struct hfs_cat_entry *entry = fork->entry;
    struct hfs_mdb *mdb = entry->mdb;
    struct hfs_extent *ext;
    int i, start, err;
    hfs_u16 need, len=0;
    hfs_u32 ablksz = mdb->alloc_blksz;
    hfs_u32 blocks, clumpablks;

    blocks = fork->psize;
    need = ablocks - blocks/ablksz;
    if (need < 1) { /* no need to grow the fork */
        return 0;
    }

    /* round up to clumpsize */
    if (entry->u.file.clumpablks) {
        clumpablks = entry->u.file.clumpablks;
    } else {
        clumpablks = mdb->clumpablks;
    }
    need = ((need + clumpablks - 1) / clumpablks) * clumpablks;

    /* find last extent record and try to extend it */
    if (!(ext = find_ext(fork, blocks/ablksz - 1))) {
        /* somehow we couldn't find the end of the file! */
        return -1;
    }

    /* determine which is the last used extent in the record */
    /* then try to allocate the blocks immediately following it */
    for (i=2; (i>=0) && !ext->length[i]; --i) {};
    if (i>=0) {
        /* try to extend the last extent */
        start = ext->block[i] + ext->length[i];

        err = 0;
        lock_bitmap(mdb);
        len = hfs_vbm_count_free(mdb, start);
        if (!len) {
            unlock_bitmap(mdb);
            goto more_extents;
        }
        if (need < len) {
            len = need;
        }
        err = hfs_set_vbm_bits(mdb, start, len);
        unlock_bitmap(mdb);
        if (err) {
            relse_ext(ext);
            return -1;
        }

        zero_blocks(mdb, start, len);

        ext->length[i] += len;
        ext->end += len;
        blocks = (fork->psize += len * ablksz);
        need -= len;
        update_ext(fork, ext);
    }

more_extents:
    /* add some more extents */
    while (need) {
        len = need;
        err = 0;
        lock_bitmap(mdb);
        start = hfs_vbm_search_free(mdb, &len);
        if (need < len) {
            len = need;
        }
        err = hfs_set_vbm_bits(mdb, start, len);
        unlock_bitmap(mdb);
        if (!len || err) {
            relse_ext(ext);
            return -1;
        }
        zero_blocks(mdb, start, len);

        /* determine which is the first free extent in the record */
        for (i=0; (i<3) && ext->length[i]; ++i) {};
        if (i < 3) {
            ext->block[i] = start;
            ext->length[i] = len;
            ext->end += len;
            update_ext(fork, ext);
        } else {
            if (!(ext = new_extent(fork, ext, blocks/ablksz,
                                   start, len, ablksz))) {
                lock_bitmap(mdb);
                hfs_clear_vbm_bits(mdb, start, len);
                unlock_bitmap(mdb);
                return -1;
            }
        }
        blocks = (fork->psize += len * ablksz);
        need -= len;
    }
    set_cache(fork, ext);
    relse_ext(ext);
    return 0;
}
Пример #10
0
/*
 * find_ext()
 *
 * Given a pointer to a (struct hfs_file) and an allocation block
 * number in the file, find the extent record containing that block.
 * Returns a pointer to the extent record on success or NULL on failure.
 * The 'cache' field of 'fil' also points to the extent so it has a
 * reference count of at least 2.
 *
 * Callers must check that fil != NULL
 */
static struct hfs_extent * find_ext(struct hfs_fork *fork, int alloc_block)
{
    struct hfs_cat_entry *entry = fork->entry;
    struct hfs_btree *tr= entry->mdb->ext_tree;
    struct hfs_ext_key target, *key;
    struct hfs_brec brec;
    struct hfs_extent *ext, *ptr;
    int tmp;

    if (alloc_block < 0) {
        ext = &fork->first;
        goto found;
    }

    ext = fork->cache;
    if (!ext || (alloc_block < ext->start)) {
        ext = &fork->first;
    }
    while (ext->next && (alloc_block > ext->end)) {
        ext = ext->next;
    }
    if ((alloc_block <= ext->end) && (alloc_block >= ext->start)) {
        goto found;
    }

    /* time to read more extents */
    if (!HFS_NEW(ext)) {
        goto bail3;
    }

    build_key(&target, fork, alloc_block);

    tmp = hfs_bfind(&brec, tr, HFS_BKEY(&target), HFS_BFIND_READ_LE);
    if (tmp < 0) {
        goto bail2;
    }

    key = (struct hfs_ext_key *)brec.key;
    if ((hfs_get_nl(key->FNum) != hfs_get_nl(target.FNum)) ||
            (key->FkType != fork->fork)) {
        goto bail1;
    }

    read_extent(ext, brec.data, hfs_get_hs(key->FABN));
    hfs_brec_relse(&brec, NULL);

    if ((alloc_block > ext->end) && (alloc_block < ext->start)) {
        /* something strange happened */
        goto bail2;
    }

    ptr = fork->cache;
    if (!ptr || (alloc_block < ptr->start)) {
        ptr = &fork->first;
    }
    while (ptr->next && (alloc_block > ptr->end)) {
        ptr = ptr->next;
    }
    if (ext->start == ptr->start) {
        /* somebody beat us to it. */
        HFS_DELETE(ext);
        ext = ptr;
    } else if (ext->start < ptr->start) {
        /* insert just before ptr */
        ptr->prev->next = ext;
        ext->prev = ptr->prev;
        ext->next = ptr;
        ptr->prev = ext;
    } else {
        /* insert at end */
        ptr->next = ext;
        ext->prev = ptr;
    }
found:
    ++ext->count; /* for return value */
    set_cache(fork, ext);
    return ext;

bail1:
    hfs_brec_relse(&brec, NULL);
bail2:
    HFS_DELETE(ext);
bail3:
    return NULL;
}