Beispiel #1
0
int charparty_auction_list_update_callback(sprite_t* p, uint32_t id, char* buf, int len)
{
	uint32_t time_left;
	uint32_t auction_cnt;
	uint32_t expect_len = sizeof(time_left) + sizeof(auction_cnt);
	CHECK_BODY_LEN_GE( len, expect_len );
	int j = 0;
	UNPKG_H_UINT32( buf, time_left, j );
	if( time_left > CHP_AUCTION_UPDATE_TIME )
	{
		time_left = 0;
	}
	else
	{
		time_left = CHP_AUCTION_UPDATE_TIME - time_left;
	}

	UNPKG_H_UINT32( buf, auction_cnt, j );
	expect_len += auction_cnt * sizeof(auction_info_t);
	CHECK_BODY_LEN( len, expect_len );
	int msg_len = sizeof(protocol_t);
	PKG_UINT32( msg, time_left, msg_len );
	PKG_UINT32( msg, auction_cnt, msg_len );
	auction_info_t* auction_info;
	int i;
	DEBUG_LOG( "=================================Charparty Auction List Update============================" );
	DEBUG_LOG( "Auction Cnt:[%u]", auction_cnt );
	for( i = 0; i < auction_cnt; ++i )
	{
		auction_info = (auction_info_t*)(buf + j );
		j += sizeof(*auction_info);
		DEBUG_LOG( "Idx:[%u] Buyer ID:[%u] Item:[%u] Prize[%u]", i, auction_info->buyer_id, auction_info->item_id, auction_info->cur_prize );
		if( auction_info->buyer_id == 0 || auction_info->cur_prize == 0 )
		{
			continue;
		}

		//统计 拍得物品的人数
		{
			uint32_t msgbuff[2]= {auction_info->buyer_id, 1};
			msglog(statistic_logfile, 0x0409C2D8, get_now_tv()->tv_sec, msgbuff, sizeof(msgbuff));
		}
		//统计 系统输出物品数量
		{
			const uint32_t item_list[] = { 1220157, 190802, 190749, 190803, 190748, 1593028, 1270055, 1270063, 1593026, 1270078,
				1270079, 1270066, 1270072, 1270073, 1270038, 1270010, 1270058, 1593034, 1593037, 1593065, 1593041, 1353296, 1353297,
				1353271, 1353223, 1353226, 1353255, 1270012, 1230044, 1230026, 1270021, 1593021, 1593061 };
			uint32_t list_cnt = sizeof(item_list)/sizeof(uint32_t);
			uint32_t msg_id = 0x0409C2D9;
			int idx;
			for( idx = 0; idx < list_cnt; ++idx )
			{
				if( auction_info->item_id == item_list[idx] )
				{
					msg_id += idx;
					uint32_t msgbuff[2]= { auction_info->buyer_id, 1 };
					msglog(statistic_logfile, msg_id, get_now_tv()->tv_sec, msgbuff, sizeof(msgbuff));
					break;
				}
			}
		}
		
		DEBUG_LOG( "ItemID:[%u] ContributorID:[%u], BuyID:[%u], Prize:[%u]", 
			auction_info->item_id, auction_info->contributor_id, auction_info->buyer_id, auction_info->cur_prize );
		//添加拍得物品,并赠送徽章
		{
			int sendlen = 0;
			uint8_t buff[128];
			PKG_H_UINT32( buff, 0, sendlen );
			PKG_H_UINT32( buff, 2, sendlen );
			PKG_H_UINT32( buff, 203, sendlen );
			PKG_H_UINT32( buff, 0, sendlen );
			
			item_kind_t* ik = find_kind_of_item(auction_info->item_id);
			item_t*it = get_item( ik, auction_info->item_id );
			pkg_item_kind( p, buff, auction_info->item_id, &sendlen );
			PKG_H_UINT32( buff, auction_info->item_id, sendlen );
			PKG_H_UINT32( buff, 1, sendlen );
			PKG_H_UINT32( buff, it->max, sendlen );

			ik = find_kind_of_item(CHP_BADGE_ITEM_ID);
			it = get_item( ik, CHP_BADGE_ITEM_ID );
			pkg_item_kind( p, buff, CHP_BADGE_ITEM_ID, &sendlen );
			PKG_H_UINT32( buff, CHP_BADGE_ITEM_ID, sendlen );
			PKG_H_UINT32( buff, 1, sendlen );
			PKG_H_UINT32( buff, it->max, sendlen );
			send_request_to_db( SVR_PROTO_EXCHG_ITEM, NULL, sendlen, buff, auction_info->buyer_id );
		}
		//拍到物品后发送邮件
		{
			item_kind_t* ik = find_kind_of_item( auction_info->item_id );
			if( !ik )
			{
				ERROR_RETURN( ("charparty_auction_list_update_callback Invalid Item ID:[%u]", auction_info->item_id), -1 );
			}
			item_t* it = get_item( ik, auction_info->item_id );
			if( !it )
			{
				ERROR_RETURN( ("charparty_auction_list_update_callback Invalid Item ID:[%u]", auction_info->item_id), -1 );
			}
			uint32_t loacl_kind;
			switch( ik->kind )
			{
				//天使种子
			case ANGEL_ITEM_KIND:
				{
					loacl_kind = CHPDT_ANGEL;
				}
				break;
			case CUTE_PIG_KIND:
				{
					loacl_kind = CHPDT_PIG;
				}
				break;
			case HOMELAND_SEED_KIND:
				//农场种子
				{
					loacl_kind = CHPDT_ARG;
				}
				break;
			case ANIMAL_BABY_ITEM:
				//牧场
				{
					loacl_kind = CHPDT_MU;
				}
				break;
			case SPECIAL_ITEM_KIND:
			case HOMELAND_ITEM_KIND:
				//其他系统提供的收集品
				{
					loacl_kind = CHPDT_COLLECT;
				}
				break;
			default:
				{
					ERROR_LOG( "charparty_auction_list_update_callback Invalid Item ID:[%u] Kind:[%u]", auction_info->item_id, ik->kind );
					continue;
				}
				break;
			}
			loacl_kind -= 1;
			char post_msg[512] = {0};
#ifndef TW_VER
			char npc_name[] = "伊莲";
			char item_pos_name[][16] = { {"家园仓库"}, {"牧场仓库"}, {"天使园仓库"}, {"猪倌背包"}, {"百宝箱"} };
			char post_msg_format[] = "恭喜你在第二届爱心天使慈善派对上成功拍下%s,已经放入你的%s了,并获得一枚慈善勋章。";
#else
			char npc_name[] = "伊蓮";
			char item_pos_name[][16] = { {"家園倉庫"}, {"牧場倉庫"}, {"天使園倉庫"}, {"豬官背包"}, {"百寶箱"} };
			char post_msg_format[] = "恭喜你在第二屆愛心天使慈善派對上成功拍下%s,已經放入你的%s了,並獲得一枚慈善勳章。";
#endif
			snprintf( post_msg, sizeof(post_msg), post_msg_format, it->name, item_pos_name[loacl_kind] );
			send_postcard( npc_name, 0, auction_info->buyer_id, 1000297, post_msg, 0 );
		}
	}
	return 0;
}
Beispiel #2
0
int get_profession_callback(sprite_t* p, uint32_t id, char* buf, int len)
{
	uint32_t guild_salary[6] = {500, 700, 1000, 1300, 1600, 2000};
	uint32_t qishi_salary[3] = {1000, 2000, 3000};
	uint32_t architect_salary[5] = {500, 600, 700, 800, 1000};
	uint32_t prof_salary[50] = {500, 500, 500, 1000, 500, 500, 500, 500,1500,500,500};
	uint32_t teach_salary[5] = {500, 700, 900, 1100, 1300};
	uint32_t dietitian_salary[5] = {500, 700, 900, 1100, 1300};
	uint32_t hunt_salary[1] = {1000};

	CHECK_BODY_LEN(len, 200);

	switch (p->waitcmd) {
	case 	PROTO_GET_PROFESSIONS:
		response_proto_str(p, p->waitcmd, len, buf, 0);
		return 0;
	case	PROTO_GET_SMC_SALARY:
	{
		p->sess_len = 0;
		uint32_t salary = 0;
		int loop;
		for (loop = 0; loop < 200; loop += 4) {
			uint32_t tmp_salary = 0;
			if (buf[loop] == 0) {
				continue;
			}
			tmp_salary = prof_salary[loop/4];
			if (loop == 0) {        // guild  salary
				if (buf[loop] > 6)
					buf[loop] = 6;
				tmp_salary = guild_salary[buf[loop] - 1];
			}
			if (loop == 12) {		// Qishi  salary
				if (buf[loop] > 3)
					buf[loop] = 3;
				tmp_salary = qishi_salary[buf[loop] - 1];
			}
			if (loop == 28) {		// architect salary
				if (buf[loop] > 5)
					buf[loop] = 5;
				tmp_salary = architect_salary[buf[loop] - 1];
			}
			if (loop == 36) {		// teacher salary
				if (buf[loop] > 5)
					buf[loop] = 5;
				tmp_salary = teach_salary[buf[loop] - 1];
			}
			if (loop == 40){		// dietitian salary
				if (buf[loop] > 5)
					buf[loop] = 5;
				tmp_salary = dietitian_salary[buf[loop] - 1];
			}
			if (loop == 44) {
				if (buf[loop] > 1)
					buf[loop] = 1;
				tmp_salary = hunt_salary[buf[loop] - 1];
			}
			if (loop == 48) {
				if (buf[loop] > 1)
					buf[loop] = 1;
				tmp_salary = 0;
			}
			salary += tmp_salary;
		}
		PKG_UINT32(p->session, salary, p->sess_len);

		uint32_t msglog_salary = salary;
    		msglog(statistic_logfile, 0x020B1102, get_now_tv()->tv_sec, &msglog_salary, sizeof(uint32_t));

		return db_change_xiaome(p, salary, ATTR_CHG_roll_back, 0, p->id);
	}
	case	PROTO_CHK_SMC_SALARY:
	{
		int j = sizeof(protocol_t);
		uint32_t salary = 0;
		int loop;
		for (loop = 0; loop < 200; loop += 4) {
			uint32_t tmp_salary = 0;
			if (buf[loop] == 0) {
				PKG_UINT32(msg, tmp_salary, j);
				continue;
			}
			tmp_salary = prof_salary[loop/4];
			if (loop == 0) {        // guild  salary
				if (buf[loop] > 6)
					buf[loop] = 6;
				tmp_salary = guild_salary[buf[loop] - 1];
			}
			if (loop == 12) {		// Qishi  salary
				if (buf[loop] > 3)
					buf[loop] = 3;
				tmp_salary = qishi_salary[buf[loop] - 1];
			}
			if (loop == 28) {		// architect salary
				if (buf[loop] > 5)
					buf[loop] = 5;
				tmp_salary = architect_salary[buf[loop] - 1];
			}
			if (loop == 36) {		// teacher salary
				if (buf[loop] > 5)
					buf[loop] = 5;
				tmp_salary = teach_salary[buf[loop] - 1];
			}
			if (loop == 40){		// dietitian salary
				if (buf[loop] > 5)
					buf[loop] = 5;
				tmp_salary = dietitian_salary[buf[loop] - 1];
			}
			if (loop == 44) {		// small hunt
				if (buf[loop] > 1)
					buf[loop] = 1;
				tmp_salary = hunt_salary[buf[loop] - 1];
			}
			salary += tmp_salary;
			PKG_UINT32(msg, tmp_salary, j);
			DEBUG_LOG("CHK SALARY[%u %u %u]", p->id, loop, tmp_salary);
		}
		PKG_UINT32(msg, salary, j);
		init_proto_head(msg, p->waitcmd, j);

		return send_to_self(p, msg, j, 1);
	}
	default:
		ERROR_RETURN(("bad cmd id[%u %u]", p->id, p->waitcmd), -1);
	}
}
Beispiel #3
0
int  init_service(int isparent)
{

	if (!isparent) {

        DEBUG_LOG("INIT_SERVICE");
	    const char *ip= get_ip_ex(0x01);
	    if ( strncmp( ip,"10.",3 )==0 ) {
	        g_is_test_env=true;
			DEBUG_LOG("=============TEST ENV TRUE =============");
	    }else{
	        g_is_test_env=false;
			DEBUG_LOG("=============TEST ENV FALSE =============");
	    }

		g_log_send_buf_hex_flag=g_is_test_env?1:0;
	



		if (sizeof(sprite_t) >= SPRITE_STRUCT_LEN - 800 || sizeof(grp_loop_t) != VIP_BUFF_LEN) {
			ERROR_RETURN(("sprite struct not big enough\t[%lu %u]", sizeof(sprite_t), SPRITE_STRUCT_LEN), -1);
		}
		srand(time(0) * get_server_id());
		setup_timer();
		INIT_LIST_HEAD(&(g_events.timer_list));
		INIT_LIST_HEAD(&active_box_list);
		if ( config_get_strval("_use_lua_config") ==NULL  ){
			config_init("./conf/common.conf");
		}

		statistic_logfile = config_get_strval("statistic_file");
		if (!statistic_logfile)
			return -1;
		if ((init_cli_proto_handles(0) == -1)	|| 
			(init_db_proto_handles(0) == -1)		||
			(init_home_handle_funs() == -1)		||
			(init_switch_handle_funs() == -1)		||
			(init_all_timer_type() == -1)			||
			(init_magic_code_proto_handles(0) == -1) ||
			(init_spacetime_code_proto_handles(0) == -1) ||
			(init_mall_proto_handles(0) == -1)
			) {
			return -1;
		}
		init_sprites();
		init_exp_lv();
		init_home_maps();
		init_all_items();
		init_beast_grp();
		init_rand_infos();
		init_npcs();
		init_all_skills();
		init_all_clothes();
		init_sys_info();
		init_all_tasks();
		init_mail();
		init_shops();
		init_vip_items();
		init_products();

		idc_type = config_get_intval("idc_type" ,1);
		KDEBUG_LOG(0, "ONLINE START\t[%lu %d]", sizeof(sprite_t), idc_type);

		if (
			//11
			(load_xmlconf("./conf/items.xml", load_items) == -1)
			|| (load_xmlconf("./conf/clothes.xml", load_clothes) == -1)
			|| (load_xmlconf("./conf/beasts.xml", load_beasts) == -1)
			//
			|| (load_xmlconf("./conf/pet_exchange.xml", load_pet_exchange) == -1)//3M
			|| (load_xmlconf("./conf/pet_exchange_egg.xml", load_pet_exchange_egg) == -1)
			//62
			|| (load_xmlconf("./conf/gplan.xml", load_rare_beasts) == -1)
			|| (load_xmlconf("./conf/titles.xml", load_honor_titles) == -1)
			|| (load_xmlconf("./conf/picsrv.xml", load_picsrv_config) == -1)
			) {
			return -1;
		}
		if (
				load_xmlconf("./conf/beastgrp.xml", load_beast_grp) == -1 
				|| (load_xmlconf("./conf/handbook.xml", load_handbook) == -1)
				|| (load_xmlconf("./conf/suits.xml", load_suit) == -1)
				|| ( load_xmlconf("./conf/maps.xml", load_maps) == -1)
				|| (load_xmlconf("./conf/rand_item.xml", load_rand_item) == -1)
				|| (load_xmlconf("./conf/vip_item.xml", load_vip_item) == -1)
				|| (load_xmlconf("./conf/commodity.xml", load_products) == -1)
				|| (load_xmlconf("./conf/skills_price.xml", load_all_skills) == -1)
				|| (load_xmlconf("./conf/tasks_new.xml", load_tasks) == -1)//task:12M
				|| (load_xmlconf("./conf/tasks_new.xml", load_task_loops) == -1)
				|| (load_xmlconf("./conf/holiday.xml", load_holiday_factor) == -1)
				|| (load_xmlconf("./conf/box.xml", load_box) == -1)
				|| (load_xmlconf("./conf/exchanges.xml", load_exchange_info) == -1)
				|| (load_xmlconf("./conf/npc.xml", load_npc) == -1)
				|| (load_xmlconf("./conf/npcSkills.xml", load_shop_skill) == -1)
				|| (load_xmlconf("./conf/npcShop.xml", load_shop_item) == -1)
				|| (load_xmlconf("./conf/mail.xml", load_sys_mail) == -1)
				|| (load_xmlconf("./conf/sysinfo.xml", load_sys_info) == -1)
				|| (load_xmlconf("./conf/fishGame.xml", load_fish_info) == -1)
				|| (load_xmlconf("./conf/professtion.xml", load_init_prof_info) == -1)
				|| (load_xmlconf("./conf/maze.xml", load_maze_xml) == -1)
				|| (load_xmlconf("./conf/mapcopy.xml", load_map_copy) == -1)
			)

			return -1;

	//	sleep(1000);
		activate_boxes();
		start_maze_timer();

		/*
		if(tm_load_dirty("./data/tm_dirty.dat") < 0){
			KERROR_LOG(0, "Failed to load drity word file!");
			return -1;
		}
		*/
		
		init_batter_teams();
		init_batter_infos();
		connect_to_switch_timely(0, 0);
		regist_timers();
		udp_report_fd = create_udp_socket(&udp_report_addr, config_get_strval("report_svr_ip"), config_get_intval("report_svr_port", 0));
		udp_post_fd = create_udp_socket(&udp_post_addr, config_get_strval("post_svr_ip"), config_get_intval("post_svr_port", 0));
		switch (idc_type) {
		case idc_type_dx:
			chat_svr_fd = create_udp_socket(&udp_chat_svr_addr, config_get_strval("dx_chat_svr_ip"), config_get_intval("chat_svr_port", 0));
			break;
		case idc_type_wt:
			chat_svr_fd = create_udp_socket(&udp_chat_svr_addr, config_get_strval("wt_chat_svr_ip"), config_get_intval("chat_svr_port", 0));
			break;
		case idc_type_internal:
		case idc_type_internal + 1:
			chat_svr_fd = create_udp_socket(&udp_chat_svr_addr, config_get_strval("in_chat_svr_ip"), config_get_intval("chat_svr_port", 0));
			break;
		default:
			return -1;
		}
	}

	return 0;
}
Beispiel #4
0
int trans_multi_file_add(uint32_t userid, uint16_t cmd, int fd, void* pkg, int pkglen) 
{
	CHECK_BODY_LEN_GE(pkglen, 12);

	int			user_fd, old_key_album, file_cnt;
	int 		j = 0;
	UNPKG_H_UINT32(pkg, user_fd, j);
	UNPKG_H_UINT32(pkg, old_key_album, j);
	UNPKG_H_UINT32(pkg, file_cnt, j);
	trans_multi_t* lptm = g_hash_table_lookup(trans_multi_maps, &user_fd);
	if (!lptm) {
		ERROR_RETURN(("not find fd\t[%u %u %u]", userid, cmd, user_fd), -1);
	}
	
	uint8_t* multi_thumbs_buff = (uint8_t*)g_slice_alloc0(MULTI_THUMB_BUFF_LEN);
	if (!multi_thumbs_buff) {
		send_err_to_php(lptm->fd, lptm->cmd, lptm->userid, err_system_fatal_err);
		do_del_conn(lptm->fd);
		g_hash_table_remove(trans_multi_maps, &lptm->fd);
		ERROR_RETURN(("not enough memory\t[%u %u]", userid, cmd), -1);
	}
	if (file_cnt != lptm->file_cnt || userid != lptm->userid || old_key_album != lptm->key_albumid) {
		ERROR_LOG("not consist\t[ad_old_key=%u th_ok=%u ad_file_cnt=%u th_fc=%u ad_user=%u th_user=%u]", 
			lptm->key_albumid, old_key_album, lptm->file_cnt, file_cnt, lptm->userid, userid);
		goto err;
	}
	
	DEBUG_LOG("TRANSFER TO\t[%u %u]", old_key_album, lptm->new_key_albumid);
	int k = sizeof(protocol_t);
	PKG_H_UINT32(multi_thumbs_buff, user_fd, k);
	PKG_H_UINT32(multi_thumbs_buff, lptm->new_key_albumid, k);
	int label_file_k = k; k += 4;
	//PKG_H_UINT32(multi_thumbs_buff, file_cnt, k);

	int loop;
	for (loop = 0; loop < lptm->file_cnt; loop++) {
		file_info_t* lfi = &lptm->fi[loop];
		CHECK_BODY_LEN_GE(pkglen, j + 4);
		int thumb_cnt = 0;
		UNPKG_H_UINT32(pkg, thumb_cnt, j);
		if (thumb_cnt != lfi->thumb_cnt) {
			ERROR_LOG("thumb_cnt err\t[userid=%u old_key=%u ad_thumb_cnt=%u th_tc=%u]", 
				userid, old_key_album, lfi->thumb_cnt, thumb_cnt);
			send_err_to_php(lptm->fd, lptm->cmd, lptm->userid, err_system_fatal_err);
			goto err;
		}
		int label_thumb_cnt_k = k; k += 4;
		//PKG_H_UINT32(multi_thumbs_buff, thumb_cnt, k);
		int lp;
		for (lp = 0; lp < lfi->thumb_cnt; lp++) {
			uint32_t  thumb_id = 0, thumb_len = 0;
			CHECK_BODY_LEN_GE(pkglen, j + 4);
			UNPKG_H_UINT32(pkg, thumb_id, j);
			if (thumb_id != lfi->sth[lp].thumb_id) {
				ERROR_LOG("thumb_id err\t[userid=%u old_key=%u idx=%u ad_thumb_id=%u th_tc=%u]", 
					userid, old_key_album, lp, lfi->sth[lp].thumb_id, thumb_id);
				send_err_to_php(lptm->fd, lptm->cmd, lptm->userid, err_system_fatal_err);
				goto err;
			}
			CHECK_BODY_LEN_GE(pkglen, j + 4);
			UNPKG_H_UINT32(pkg, thumb_len, j);
			if (lfi->ret == err_not_find_thumb) {
				CHECK_BODY_LEN_GE(pkglen, j + thumb_len);
				j += thumb_len;
				continue;
			}
				
			if (!thumb_len) {
				lfi->ret = err_not_find_thumb;
			} else {
				DEBUG_LOG("TRAN ADD\t[id=%u len=%u]", thumb_id, thumb_len);
				PKG_H_UINT32(multi_thumbs_buff, thumb_id, k);
				PKG_H_UINT32(multi_thumbs_buff, thumb_len, k);
				CHECK_BODY_LEN_GE(pkglen, j + thumb_len);
				UNPKG_STR(pkg, multi_thumbs_buff + k, j, thumb_len);
				k += thumb_len;
			}
		}
		if (!lfi->ret) {
			PKG_H_UINT32(multi_thumbs_buff, thumb_cnt, label_thumb_cnt_k);
		} else {
			k = label_thumb_cnt_k; file_cnt--;
		}
	}
	PKG_H_UINT32(multi_thumbs_buff, file_cnt, label_file_k);

	init_proto_head(multi_thumbs_buff, userid, proto_ts_trans_multi_add_thumbs, k);
	if (send_to_thumbserv(multi_thumbs_buff, k, lptm->new_key_albumid) == -1) {
		send_err_to_php(lptm->fd, lptm->cmd, userid, err_thumbserv_net_err);
		goto err;
	}
	g_slice_free1(MULTI_THUMB_BUFF_LEN, multi_thumbs_buff);
	return 0;
err:
	do_del_conn(lptm->fd);
	g_slice_free1(MULTI_THUMB_BUFF_LEN, multi_thumbs_buff);
	g_hash_table_remove(trans_multi_maps, &lptm->fd);
	return -1;
}
Beispiel #5
0
int get_sports_team_callback(sprite_t* p, uint32_t id, char* buf, int len)
{
    typedef struct _sport_info {
        uint32_t team;
        uint32_t total_medal[3];
        uint32_t day_medal[3];
    } sport_info_t;
    CHECK_BODY_LEN(len, sizeof(sport_info_t));
    sport_info_t* my_sport_info = (sport_info_t*)buf;
    DEBUG_LOG("SPORTS SELF INFO [%d %d %d %d %d %d %d %d]", p->id, p->waitcmd, my_sport_info->total_medal[0],my_sport_info->total_medal[1],my_sport_info->total_medal[2],my_sport_info->day_medal[0],my_sport_info->day_medal[1],my_sport_info->day_medal[2]);
    switch(p->waitcmd) {
    case PROTO_LOGIN:
        p->tmpinfo.team = my_sport_info->team;
        if(p->tmpinfo.team >5) {
            ERROR_LOG("error team [%d %d]", p->id, p->tmpinfo.team);
            p->tmpinfo.team = 5;
        }
        // DEBUG_LOG("MY TEAM [%d %d]", p->id, p->tmpinfo.team);
        return sports_get_npc_info(p);
    //return proc_final_login_step(p);
    case PROTO_SPORT_BREAK:
    {
        uint32_t type = *(uint32_t*)p->session;
        if(my_sport_info->total_medal[type]) {
            static int break_reward[3] = {12832, 12833, 12834};
            *(uint32_t*)(p->session + 4) = break_reward[type];
            db_single_item_op(p, p->id, break_reward[type], 1, 1);
        } else {
            return send_to_self_error(p, p->waitcmd, -ERR_sports_no_medal, 1);
        }
    }
    break;
    case PROTO_SPORT_REACH_MAX:
    {
        uint32_t type = *(uint32_t*)p->session;
        static int max_medal[3] = {10, 15, 20};
        static int max_medal_type[3] = {133, 137, 138};
        //       DEBUG_LOG("REACH MAX INFO [%d %d]", p->id, my_sport_info->day_medal[type], max_medal[type] );
        if(my_sport_info->day_medal[type] >= max_medal[type]) {
            return db_set_sth_done(p, max_medal_type[type], 1);
        } else {
            return send_to_self_error(p, p->waitcmd, -ERR_sports_reach_max, 1);
        }
    }
    break;
    case PROTO_SPORT_SELF_INFO:
    {
        int l = sizeof(protocol_t);
        PKG_UINT32(msg, my_sport_info->total_medal[0], l);
        PKG_UINT32(msg, my_sport_info->total_medal[1], l);
        PKG_UINT32(msg, my_sport_info->total_medal[2], l);
        PKG_UINT32(msg, my_sport_info->day_medal[0], l);
        PKG_UINT32(msg, my_sport_info->day_medal[1], l);
        PKG_UINT32(msg, my_sport_info->day_medal[2], l);
        init_proto_head(msg, p->waitcmd, l);
        return send_to_self(p, msg, l, 1);
    }
    break;
    default:
        ERROR_RETURN(("err waitcmd [%d %d]", p->id, p->waitcmd), -1);
    }
    return 0;
}
Beispiel #6
0
/* add header elements for async mode */
int
AddAsyncHeader(OpenSOAPEnvelopePtr *request) {
	static char FuncName[] = "AddAsyncHeader";
    int error = OPENSOAP_NO_ERROR;
	OpenSOAPBlockPtr header;
	OpenSOAPXMLElmPtr ttlElm = NULL;
	OpenSOAPStringPtr typeStr = NULL;
	OpenSOAPStringPtr asyncStr = NULL;
	OpenSOAPXMLElmPtr asyncElm = NULL;
		
	/* add opensoap-header block */
	error = OpenSOAPEnvelopeAddHeaderBlockMB(*request,
											 "opensoap-header-block",
											 &header); 
	ERROR_RETURN(error, FuncName, "add header part");
	
	/* set namespace to opensoap-header block */
	error = OpenSOAPBlockSetNamespaceMB(header,
										OPENSOAP_HEADER_NS_URI,
										OPENSOAP_HEADER_NS_PREFIX);
	ERROR_RETURN(error, FuncName, "set namespace to header part");
	
	/* set ttl element to opensoap-header */
	error = OpenSOAPBlockSetChildValueMB(header, "ttl", "int", &ttl);
	ERROR_RETURN(error, FuncName, "set ttl element");
	
	/* set namespace to ttl element */
	error = OpenSOAPBlockGetChildMB(header, "ttl", &ttlElm);
	ERROR_RETURN(error, FuncName, "get ttl element");
	
	error = OpenSOAPXMLElmSetNamespaceMB(ttlElm,
										 OPENSOAP_HEADER_NS_URI,
										 OPENSOAP_HEADER_NS_PREFIX);
	ERROR_RETURN(error, FuncName, "set namespace to ttl element");
	
	/* add type attribute with namespace to ttl element */
	
	error = OpenSOAPStringCreateWithMB("second", &typeStr);
	ERROR_RETURN(error, FuncName, "create string for type attr");
	
	error = AddAttributeWithNamespace(header,
									  "ttl",
									  "type",
									  "string",
									  &typeStr,
									  OPENSOAP_HEADER_NS_URI,
									  OPENSOAP_HEADER_NS_PREFIX);
	ERROR_RETURN(error, FuncName, "add type attr to ttl element");
	
	/* add async element */
	
	error = OpenSOAPStringCreateWithMB("true", &asyncStr);
	ERROR_RETURN(error, FuncName, "create string for async");
	
	error = OpenSOAPBlockSetChildValueMB(header, "async", "string", &asyncStr);
	ERROR_RETURN(error, FuncName, "set async element");
	
	/* set namespace to async element */
	
	error = OpenSOAPBlockGetChildMB(header, "async", &asyncElm);
	ERROR_RETURN(error, FuncName, "get async element");
	
	error = OpenSOAPXMLElmSetNamespaceMB(asyncElm,
										 OPENSOAP_HEADER_NS_URI,
										 OPENSOAP_HEADER_NS_PREFIX);
	ERROR_RETURN(error, FuncName, "set namespace to async element");
	
	return error;
}
Beispiel #7
0
int EffectMgr::LoadEffectInfo()
{
    int ret = 0;
    xmlDocPtr doc;
    xmlNodePtr root;
    xmlNodePtr nodeEffect;
    int effectCount = 0;
    char file[] = "./conf/angelfight/effectinfo.xml";

    doc = xmlParseFile(file);
    if (!doc)
    {
        ERROR_RETURN( ( "EffectMgr::LoadEffectInfo() Open [%s] Failed", file ), -1 );
    }

    root = xmlDocGetRootElement(doc);
    if ( !root )
    {
        ERROR_LOG("xmlDocGetRootElement error");
        ret = -1;
        goto exit;
    }
    //状态总数
    DECODE_XML_PROP_INT( effectCount, root, "Count" );
    if( effectCount <= 0 )
    {
        goto exit;
    }

    m_vecEffect.clear();
    m_vecEffect.reserve(effectCount);

    //获取子节点
    nodeEffect= root->xmlChildrenNode;
    Effect* pEffect;
    while( nodeEffect )
    {
        if ( 0 == xmlStrcmp( nodeEffect->name, BAD_CAST"Effect" ) )
        {
            xmlChar* str;

            str = xmlGetProp( nodeEffect, BAD_CAST"Type" );
            if( str )
            {
                if( 0 == xmlStrcmp( str, BAD_CAST"HP" ) )
                {
                    pEffect = new EModHp();
                }
                else if( 0 == xmlStrcmp( str, BAD_CAST"DEF" ) )
                {
                    pEffect = new EModDef();
                }
                else if( 0 == xmlStrcmp( str, BAD_CAST"HIT" ) )
                {
                    pEffect = new EModHit();
                }
                else if( 0 == xmlStrcmp( str, BAD_CAST"CRIT" ) )
                {
                    pEffect = new EModCrit();
                }
                else if( 0 == xmlStrcmp( str, BAD_CAST"ATK" ) )
                {
                    pEffect = new EModAtk();
                }
                else if( 0 == xmlStrcmp( str, BAD_CAST"ASPD" ) )
                {
                    pEffect = new EModAspd();
                }
                else if( 0 == xmlStrcmp( str, BAD_CAST"MP" ) )
                {
                    pEffect = new EModMp();
                }
                else if( 0 == xmlStrcmp( str, BAD_CAST"EVAD" ) )
                {
                    pEffect = new EModEvad();
                }
                else if( 0 == xmlStrcmp( str, BAD_CAST"BLOCK" ) )
                {
                    pEffect = new EModBlock();
                }
                else
                {
                    xmlFree(str);
                    nodeEffect = nodeEffect->next;
                    continue;
                }
            }
            xmlFree(str);

            if( !pEffect )
            {
                DEBUG_LOG( "Malloc Effect Object Failed" );
                nodeEffect = nodeEffect->next;
                continue;
            }

            m_vecEffect.push_back( pEffect );

            uint32_t ID;
            DECODE_XML_PROP_INT( ID, nodeEffect, "ID" );
            if( ID != m_vecEffect.size() - 1 )
            {
                ERROR_LOG( "Effect ID Invalid The Value is:[%d] Expect:[%lu]", ID, m_vecEffect.size() - 1 );
            }

            str = xmlGetProp( nodeEffect, BAD_CAST"Value" );
            pEffect->XmlSetEffect( (char*)str );
            xmlFree(str);

            xmlNodePtr child = nodeEffect->xmlChildrenNode;
            Condition* pCond = NULL;
            while( child )
            {
                if( 0 == xmlStrcmp( child->name, BAD_CAST"Condition" ) )
                {
                    str = xmlGetProp( child, BAD_CAST"Type" );
                    if( str )
                    {
                        if( 0 == xmlStrcmp( str, BAD_CAST"HP" ) )
                        {
                            pCond = new CondHP();
                        }
                        else if( 0 == xmlStrcmp( str, BAD_CAST"RAND" ) )
                        {
                            pCond = new CondRand();
                        }
                        else
                        {
                            child = child->next;
                            xmlFree(str);
                            continue;
                        }
                    }
                    xmlFree(str);
                    if( !pCond )
                    {
                        DEBUG_LOG( "Malloc Condition Object Failed" );
                        child = child->next;
                        continue;
                    }
                    pEffect->AddCondition( pCond );

                    str = xmlGetProp( child, BAD_CAST"Except" );
                    pCond->XmlSetExpect( (char*)str );
                    xmlFree(str);
                }
                child = child->next;
            }
        }
        nodeEffect = nodeEffect->next;
    }
exit:
    xmlFreeDoc(doc);
    DEBUG_LOG( "Load Effect Info Over Effect Size Is:[%lu]", m_vecEffect.size() );
    return ret;
}
Beispiel #8
0
static int send_cdn_ip_2_dbserver(char *mmap_p)
{
	mmap_file_head_t *file_head_p = (mmap_file_head_t*)mmap_p;
	cdn_speed_ip_t *cdn_ip_p = (cdn_speed_ip_t*)(mmap_p + sizeof(mmap_file_head_t));
	uint8_t buf[BUF_NET_SEND_LEN];
	int len;
	uint32_t i;
	uint32_t send_count=0;
	uint32_t ready = file_head_p->ready_num;
	int number;// = cdn_ip_p->project_number;
	uint32_t packet_tag = tmp_packet_tag << SHIFT_BITS;
	int now;

resend_cdnip:
	ready -= send_count;
	send_count = 0;
	now = (int)time(0);
	for (i = 0; i < file_head_p->records_num; i++) {

		(cdn_ip_p + i)->t_time = (cdn_ip_p + i)->time[(cdn_ip_p + i)->step];
		(cdn_ip_p + i)->t_speed = (cdn_ip_p + i)->speed[(cdn_ip_p + i)->step];
		(cdn_ip_p + i)->t_count = (cdn_ip_p + i)->count[(cdn_ip_p + i)->step];

		//start-added by singku for remove ip which is out of date 2011-08-04
		if ((cdn_ip_p + i)->t_count == 0 && (cdn_ip_p + i)->ip != 0
				&& (now - (int)((cdn_ip_p + i)->t_time)) > 86400)	{
			//i如果此处有ip记录ip不为0,说明还没有到空白记录处,则判断该ip是否过期 ,一天都无数据 则删除.
			//先从hash表中删除当前ip.
			int proj = ((cdn_ip_p + i)->project_number - 1) % max_project_number;
			//tmp指向最后一个结果,将最后一个结果搬移过来,覆盖此处的数据.
			cdn_speed_ip_t *tmp = (cdn_speed_ip_t *)(cdn_speed_ip_mmap[proj].mmap_p);
			cdn_speed_ip_t *cur = tmp + i;
			pthread_spin_lock(&lock_cdn_ip);
			if (cur->t_count == 0 && (i+1) < cdn_speed_ip_mmap[proj].records_num) {//如果对应的当前mmap中该cdn ip也无数据
				tmp += (cdn_speed_ip_mmap[proj].records_num -1);
				g_hash_table_remove(cdn_hash_ip[proj], &(cur->ip));
				if (cur != tmp) {
					memcpy(cur, tmp, sizeof(cdn_speed_ip_t));
					cur->offset = i;//重置offset
					//重新插入hash表 replace会替代老的key,value,所以不用担心没有remove掉原来的末尾ip.
					g_hash_table_replace(cdn_hash_ip[proj], &(cur->ip), &(cur->offset));
				}
				if (cdn_speed_ip_mmap[proj].records_num > 0) {
					cdn_speed_ip_mmap[proj].records_num --;
					cdn_speed_ip_mmap[proj].mmap_head->records_num --;
				}
			}
			pthread_spin_unlock(&lock_cdn_ip);
		}
		//end-added by singku for remove ip which is out of date 2011-08-04

		if ((cdn_ip_p + i)->t_count == 0)
			continue;

		/*start---added by singku for cache 11-07-27*/
		if (other_start == 1)
			update_cache(proto_cache_cdn_node, (void*)(cdn_ip_p + i));
		/*end ----added by singku for cache 11-07-27*/

		//init protocol_head;
		number = ((cdn_ip_p + i)->project_number-1) % max_project_number + 1;
		len = sizeof(protocol_t) + sizeof(proto_cdn_speed_ip_t);
		init_proto_head(buf, len, proto_as_cdn_report_ip, (packet_tag + number), i, 0);

		DEBUG_LOG("SEND CDN IP PACKET___PROTO:%x,ID:%u,Number:%u,Time:%u,Speed:%u,Count:%u",
				proto_as_cdn_report_ip,i,number,(cdn_ip_p+i)->t_time,
				(cdn_ip_p+i)->t_speed/(cdn_ip_p+i)->t_count, (cdn_ip_p+i)->t_count);
		memcpy(buf + sizeof(protocol_t), &((cdn_ip_p + i)->project_number), sizeof(proto_cdn_speed_ip_t));
		if (send_data(buf, len, proto_as_cdn_report_ip) == -1)
			return -1;

		send_count ++;
		if (send_count == ready)
			break;
	}

	if (send_count == 0)
		ERROR_RETURN(("SEND COUNT == 0:map_tag:%u,type:CDN IP", tmp_packet_tag), 0);
	if (wait_all_tmpdata_ok(mmap_p) == -1) {
		ERROR_LOG("CDN IP:WAIT RET PACKETS TIME OUT");
		goto resend_cdnip;
	}

	return 0;
}
Beispiel #9
0
int set_url_mmap(char *buf, uint32_t data_len)
{
	fcgi_packet_t *packet = (fcgi_packet_t*)buf;
	static struct timeval now;
	gettimeofday(&now, NULL);

	if(data_len < (sizeof(fcgi_packet_common_t) + sizeof(a_url.count) + sizeof(a_url.page_id)
						+ packet->record.m_url.count * sizeof(a_url.vlist[0])))
		return 0;//ERROR_RETURN(("BAD URL PACKETS"), 0);

    if (ignore_project[packet->project_number] == 1)
        return 0;

	if (packet->record.m_url.count == 0 || packet->record.m_url.count > MAX_POINT)
		return 0;//ERROR_RETURN(("BAD URL PACKET"), 0);

	DEBUG_LOG("GET URL PACKET:time=%u,proj=%u,client=%u,page=%u,vcount=%u,v[0]=%u",packet->test_time,
			packet->project_number,packet->client_ip,packet->record.m_url.page_id,
			packet->record.m_url.count,packet->record.m_url.vlist[0]);

	uint32_t counter = 0, ccc = 0;
	int n = 0;
	char str[1024];
	for (counter = 0; counter < packet->record.m_url.count; counter ++) {
		if (packet->record.m_url.vlist[counter] > 100000) {
			for (ccc = 0; ccc < packet->record.m_url.count; ccc ++)
				n += sprintf(str + n, " %u", packet->record.m_url.vlist[ccc]);
			break;
		}
	}
	if (ccc != 0)
		ERROR_RETURN(("GET URL PACKET:time=%u,proj=%u,client=%u,page=%u,vcount=%u,list:%s",					packet->test_time,
				packet->project_number,packet->client_ip,packet->record.m_url.page_id,
				packet->record.m_url.count, str), 0);

	uint32_t *offset;
	uint32_t isp_key;
	code_t code;

	if (g_ipDict.find(packet->client_ip, code, &isp_key)== false)
		return 0;
    if (code.province_code == 830000)//国外
        return 0;

	offset = (uint32_t*)g_hash_table_lookup(hash_cityisp, code.key);
	if (offset == NULL)
		return 0;

	if (((int)(now.tv_sec) - (int)(packet->test_time)) > CDN_TIME_INTER*60) {
		int len = sizeof(protocol_t) + sizeof(proto_url_test_fixed_t);
		int vlen = packet->record.m_url.count * sizeof(packet->record.m_url.vlist[0]);

		init_proto_head(buf, len + vlen, proto_as_url_stat_page_time, 0, 0, 0);
		forward_url = (proto_url_test_fixed_t*)(buf + sizeof(protocol_t));
		forward_url->project_number = packet->project_number;
		forward_url->page_id = packet->record.m_url.page_id;
		forward_url->provice_code = code.province_code;
		forward_url->city_code = code.city_code;
		forward_url->isp_id = code.isp_id;
		memcpy(forward_url->isp, code.isp, ISP_LEN);
		forward_url->test_time = packet->test_time;
		forward_url->count = 1;
		forward_url->v_count = packet->record.m_url.count;
		memcpy(buf + sizeof(protocol_t) + sizeof(proto_url_test_fixed_t), packet->record.m_url.vlist, vlen);
		send_data(url_forward_buf, (len + vlen), proto_as_url_stat_page_time);
	}


	//added by singku 2011-08-30 for url raw data forward----start
	init_proto_head(url_forward_buf, sizeof(protocol_t) + data_len,
			proto_as_url_stat_forward, 0, 0, 0);
	memcpy(url_forward_buf + sizeof(protocol_t), buf, data_len);
	send_data(url_forward_buf, sizeof(protocol_t) + data_len, proto_as_url_stat_forward);
	//added by singku 2011-08-30 for url raw data forward----end

	int proj_id = (packet->project_number - 1) % max_project_number;
	int page_id = packet->record.m_url.page_id;
	int *page_index;
	int page_offset;
	int pos;
	page_index = (int*)g_hash_table_lookup(url_page_index[proj_id], &page_id);
	if (page_index == NULL) {
		if (url_page_status[proj_id].used_count == max_page_per_proj)
			ERROR_RETURN(("PROJ %d's URL PAGE IS RUNNING OUT",packet->project_number), 0);
		else {
			page_offset = find_available_url_page(proj_id);
			if (page_offset == -1)
				ERROR_RETURN(("PROJ %d's URL PAGE IS NOT RUNNING OUT,BUT CANT FIND USABLE PAGE",
						packet->project_number), 0);
			pos = proj_id * max_page_per_proj + page_offset;
			url_page_mmap[pos].mmap_head->key = page_id;
			url_page_mmap[pos].mmap_head->value = page_offset;
			url_page_mmap[pos].key = page_id;
			url_page_mmap[pos].value = page_offset;
			g_hash_table_insert(url_page_index[proj_id],
					&(url_page_mmap[pos].key),&(url_page_mmap[pos].value));
			url_page_status[proj_id].used_count ++;
			url_page_status[proj_id].status[page_offset] = 1;
		}

	}
	else {
		page_offset = *page_index;
		pos = proj_id * max_page_per_proj + page_offset;
	}

	if (packet->test_time > url_page_mmap[pos].latest_time) {
		url_page_mmap[pos].latest_time = packet->test_time;
		url_page_mmap[pos].mmap_head->latest_time = packet->test_time;
	}
	url_test_t *url_test_p = (url_test_t*)url_page_mmap[pos].mmap_p;


	url_test_p += *offset;
	if (url_test_p->count == 0) {
		url_page_mmap[pos].ready_num++;
		url_page_mmap[pos].mmap_head->ready_num++;
		url_test_p->page_id = packet->record.m_url.page_id;
		url_test_p->project_number = packet->project_number;
		memset(url_test_p->vlist, 0x0, sizeof(url_test_p->vlist));
	}
	int k;
	for(k = 0; k < (int)packet->record.m_url.count && k < MAX_POINT; k++){
		url_test_p->vlist[k] += packet->record.m_url.vlist[k];
	}
	url_test_p->v_count = packet->record.m_url.count;
	url_test_p->test_time = max(url_test_p->test_time, packet->test_time);
	url_test_p->count ++;

	return 0;
}
Beispiel #10
0
int backup_mmap_file(void* owner, void* data)
{
	//转储MMAP文件并发送该文件
	char filepath[DIR_PATH_LEN];
   char newpath[DIR_PATH_LEN];
	uint32_t i, j, pos;
	struct tm p;
	uint64_t sec;
	FILE *fp;
	//按时间、类型、项目号来备份mmap
	sec = time((time_t*)NULL);
	localtime_r((const time_t*)&sec,&p);
	//备份cdn的mmap
	for (i = 0; i < max_project_number; i++) {
		if (cdn_speed_ip_mmap[i].mmap_head->ready_num != 0) {
			snprintf(filepath, sizeof(filepath),
					"%s/tmp.mmap_backup_file_cdn_ip_[%03d]%04d-%02d-%02d-%02d-%02d-%02d",
					mmap_tmpfile_dirpath, i + 1, p.tm_year + 1900, p.tm_mon + 1, p.tm_mday,
					p.tm_hour, p.tm_min, p.tm_sec);
			snprintf(newpath, sizeof(newpath),
					"%s/mmap_backup_file_cdn_ip_[%03d]%04d-%02d-%02d-%02d-%02d-%02d",
					mmap_tmpfile_dirpath, i + 1, p.tm_year + 1900, p.tm_mon + 1,p.tm_mday,
					p.tm_hour, p.tm_min, p.tm_sec);
				 fp = fopen(filepath, "wb+");
			if (fp == NULL)
				ERROR_RETURN(("can't open backup file %s",filepath), -1);

			if (fwrite(cdn_speed_ip_mmap[i].mmap_head, 1, cdn_mmap_size_ip + MMAP_FILE_HEAD_LEN, fp)
					!= (cdn_mmap_size_ip + MMAP_FILE_HEAD_LEN)) {
				ERROR_LOG("BACK UP CDN IP MMAP FILE ERROR:proj:%u,records:%u,ready:%u", i,
						cdn_speed_ip_mmap[i].mmap_head->records_num,cdn_speed_ip_mmap[i].mmap_head->ready_num);
				fclose(fp);
				remove(filepath);
			} else {
				fclose(fp);
				rename(filepath, newpath);
				cdn_speed_ip_mmap[i].ready_num = cdn_speed_ip_mmap[i].mmap_head->ready_num = 0;

				cdn_speed_ip_t *ptr = (cdn_speed_ip_t*)cdn_speed_ip_mmap[i].mmap_p;
				for (j = 0; j < cdn_speed_ip_mmap[i].mmap_head->records_num; j++) {
					pos = (ptr + j)->step;
					(ptr + j)->speed[pos] = 0;
					(ptr + j)->count[pos] = 0;
					memset((ptr + j)->speed_distribution[pos], 0, sizeof((ptr + j)->speed_distribution[pos]));
					pos = (pos + 1) % CDN_TIME_INTER;
					if ((ptr + j)->count[pos] != 0) {
						(ptr + j)->time[pos] = (ptr + j)->time[(ptr + j)->step] + 60;
						cdn_speed_ip_mmap[i].ready_num ++;
						cdn_speed_ip_mmap[i].mmap_head->ready_num ++;
					}
					(ptr + j)->step = pos;
				}
			}
		}
		if (cdn_speed_area_mmap[i].mmap_head->ready_num != 0) {
			snprintf(filepath, sizeof(filepath),
					"%s/tmp.mmap_backup_file_cdn_area_[%03d]%04d-%02d-%02d-%02d-%02d-%02d",
					mmap_tmpfile_dirpath, i + 1, p.tm_year + 1900, p.tm_mon + 1, p.tm_mday,
					p.tm_hour, p.tm_min, p.tm_sec);
			snprintf(newpath, sizeof(newpath),
					"%s/mmap_backup_file_cdn_area_[%03d]%04d-%02d-%02d-%02d-%02d-%02d",
					mmap_tmpfile_dirpath, i + 1, p.tm_year + 1900, p.tm_mon + 1, p.tm_mday,
					p.tm_hour, p.tm_min, p.tm_sec);
			fp = fopen(filepath, "wb+");
			if (fp == NULL)
				ERROR_RETURN(("can't open backup file %s",filepath), -1);
			if (fwrite(cdn_speed_area_mmap[i].mmap_head, 1, cdn_mmap_size_area + MMAP_FILE_HEAD_LEN, fp)
					!= (cdn_mmap_size_area + MMAP_FILE_HEAD_LEN)) {
				ERROR_LOG("BACK UP CDN AREA MMAP FILE ERROR:proj:%u,records:%u,ready:%u", i,
						cdn_speed_area_mmap[i].mmap_head->records_num,cdn_speed_area_mmap[i].mmap_head->ready_num);
				fclose(fp);
				remove(filepath);
			} else {
				fclose(fp);
				rename(filepath, newpath);
				cdn_speed_area_mmap[i].ready_num = cdn_speed_area_mmap[i].mmap_head->ready_num = 0;

				cdn_speed_area_t *ptr = (cdn_speed_area_t*)cdn_speed_area_mmap[i].mmap_p;
                INFO_LOG("BBBB: cdn_speed_area_mmap[%d].mmap_head->records_num: %u",
                        i,  cdn_speed_area_mmap[i].mmap_head->records_num);
				for (j = 0; j < cdn_speed_area_mmap[i].mmap_head->records_num; j++) {
					pos = (ptr + j)->step;

                    //comments////////////////////////////////////////////////////////////////
                    cdn_speed_area_t *p_cdn_area = ptr + j;
                    if (p_cdn_area->count[pos] != 0 || p_cdn_area->t_count != 0)
                    {
                        INFO_LOG("BBBB:time[%u] speed[%u] count[%u]",
                                p_cdn_area->t_time, p_cdn_area->t_speed, p_cdn_area->t_count);
                        INFO_LOG("BBBB:pos[%u] time[%u] speed[%u] count[%u]",
                                pos, p_cdn_area->time[pos], p_cdn_area->speed[pos], p_cdn_area->count[pos]);
                        int m = 0;
                        for (m = 0; m < 6; m++)
                        {
                            INFO_LOG("BBBB:pos[%u] dis[%d]: %u", pos, m, p_cdn_area->speed_distribution[pos][m]);
                        }
                        int next_pos = (pos + 1) % CDN_TIME_INTER;
                        INFO_LOG("BBBB:next_pos[%u] time[%u] speed[%u] count[%u]",
                                next_pos, p_cdn_area->time[next_pos], 
                                p_cdn_area->speed[next_pos], p_cdn_area->count[next_pos]);
                        for (m = 0; m < 6; m++)
                        {
                            INFO_LOG("BBBB:next_pos[%u] dis[%d]: %u", 
                                    next_pos, m, p_cdn_area->speed_distribution[next_pos][m]);
                        }
                    }
                    /**
                    */
                    //////////////////////////////////////////////////////////////////////////

					(ptr + j)->count[pos] = 0;
					(ptr + j)->speed[pos] = 0;
					memset((ptr + j)->speed_distribution[pos], 0, sizeof((ptr + j)->speed_distribution[pos]));
					pos = (pos + 1) % CDN_TIME_INTER;
					if ((ptr + j)->count[pos] != 0) {
						(ptr + j)->time[pos] = (ptr + j)->time[(ptr + j)->step] + 60;
						cdn_speed_area_mmap[i].ready_num ++;
						cdn_speed_area_mmap[i].mmap_head->ready_num ++;
					}
					(ptr + j)->step = pos;
				}
			}
		}
	}
	//备份url的mmap
	int now = (int)time((time_t*)NULL);
	for (i = 0; i < max_project_number; i++) {
		for (j = 0; j < max_page_per_proj; j++) {
			pos = i * max_page_per_proj + j;
			if (url_page_mmap[pos].mmap_head->ready_num != 0) {
				snprintf(filepath, sizeof(filepath),
						"%s/tmp.mmap_backup_file_url_page_[%03d_%d]%04d-%02d-%02d-%02d-%02d-%02d",
						mmap_tmpfile_dirpath, i + 1, url_page_mmap[pos].mmap_head->key,
						p.tm_year + 1900, p.tm_mon + 1, p.tm_mday,
						p.tm_hour, p.tm_min, p.tm_sec);
				snprintf(newpath, sizeof(newpath),
						"%s/mmap_backup_file_url_page_[%03d_%d]%04d-%02d-%02d-%02d-%02d-%02d",
						mmap_tmpfile_dirpath, i + 1, url_page_mmap[pos].mmap_head->key,
						p.tm_year + 1900, p.tm_mon + 1, p.tm_mday,
						p.tm_hour, p.tm_min, p.tm_sec);
				fp = fopen(filepath, "wb+");
				if (fp == NULL)
					ERROR_RETURN(("can't open backup file %s",filepath), -1);
				if (fwrite(url_page_mmap[pos].mmap_head, 1, url_mmap_size_page + MMAP_FILE_HEAD_LEN, fp)
						!= (url_mmap_size_page + MMAP_FILE_HEAD_LEN)) {
					ERROR_LOG("BACK UP URL MMAP FILE ERROR:proj:%u,records:%u,ready:%u", url_page_mmap[pos].value,
							url_page_mmap[pos].mmap_head->records_num,url_page_mmap[pos].mmap_head->ready_num);
					fclose(fp);
					remove(filepath);
				} else {
					fclose(fp);
					rename(filepath, newpath);
					url_page_mmap[pos].ready_num = url_page_mmap[pos].mmap_head->ready_num = 0;
					uint32_t k;
					url_test_t *p = (url_test_t*)url_page_mmap[pos].mmap_p;
					for (k = 0; k < url_page_mmap[pos].mmap_head->records_num; k++)
						(p + k)->count = 0;
				}
			} else if ((now - (int)(url_page_mmap[pos].latest_time)) > 86400) {//mmap一天没用,则回收.
				g_hash_table_remove(url_page_index[i], &(url_page_mmap[pos].key));
				url_page_mmap[pos].key = url_page_mmap[pos].mmap_head->key = 0;
				url_page_mmap[pos].value = url_page_mmap[pos].mmap_head->value = 0;
				url_page_mmap[pos].latest_time = url_page_mmap[pos].mmap_head->latest_time = 0;
				url_page_mmap[pos].ready_num = url_page_mmap[pos].mmap_head->ready_num = 0;
				url_page_status[i].status[url_page_mmap[pos].value] = 0;
				if (url_page_status[i].used_count > 0)
					url_page_status[i].used_count --;
			}
		}
	}
	//下一个整点分钟时间继续触发事件
	if (data == NULL) {
		ADD_TIMER_EVENT(&g_timer, backup_mmap_file, NULL,
			get_now_tv()->tv_sec + 60 * backup_interval - get_now_tv()->tv_sec % 60);
	}

	return 0;
}
Beispiel #11
0
int set_cdn_mmap(char *buf, uint32_t data_len)
{
    int k;
	cdn_speed_ip_t *cdn_ip_p;
	cdn_speed_area_t *cdn_area_p;
	cdn_speed_area_t *tmp_for_cdn_node;
	static struct timeval start ={0, 0};
	static struct timeval now ={0, 0};
	static uint64_t recv_cdn = 0;
	uint32_t	isp_key;
	code_t code_client, code_cdn;
	bool find_client = false;
	bool speed_invalid = false;
	fcgi_packet_t *packet = (fcgi_packet_t*)buf;

	if(data_len != (sizeof(fcgi_packet_common_t) + sizeof(fcgi_cdn_t)))
		ERROR_RETURN(("BAD CDN PACKETS"), 0);

	if (start.tv_sec == 0)
		gettimeofday(&start, NULL);
	gettimeofday(&now, NULL);

    if (ignore_project[packet->project_number] == 1)
        return 0;

	++recv_cdn;
	if (!(start.tv_sec == now.tv_sec && start.tv_usec == now.tv_usec))
		DEBUG_LOG("TOTAL_RECVED_CDN_PACKETS:%lu,CDN/DAY=%.2f", recv_cdn,
				recv_cdn/(((now.tv_sec - start.tv_sec)*1000000 + now.tv_usec - start.tv_usec)/(86400*1000000.0)));

    if (packet->record.m_cdn.speed == 0)
        packet->record.m_cdn.speed = CDN_SPEED_INVALID;

	if (packet->project_number == 0
		|| (packet->record.m_cdn.speed > cdn_max_speed && packet->record.m_cdn.speed != CDN_SPEED_INVALID))
		return 0;
	if (packet->record.m_cdn.speed == CDN_SPEED_INVALID)
		speed_invalid = true;

	if (speed_invalid) {
		DEBUG_LOG("GET CDN PACKET:time=%u,proj=%u,client=%u,cdn=%u,speed=-1",packet->test_time,
			packet->project_number,packet->client_ip,packet->record.m_cdn.cdn_ip);
	} else {
		DEBUG_LOG("GET CDN PACKET:time=%u,proj=%u,client=%u,cdn=%u,speed=%u",packet->test_time,
			packet->project_number,packet->client_ip,packet->record.m_cdn.cdn_ip,packet->record.m_cdn.speed);
	}

	if (g_ipDict.find(packet->client_ip, code_client, &isp_key) == true)
		find_client = true;
    if (code_client.province_code == 830000)//国外
        return 0;

	if (((int)(now.tv_sec) - (int)(packet->test_time)) > CDN_TIME_INTER*60 && speed_invalid == false) {
		//old数据 直接转发,统计数据加和,需要过滤掉speed=-1的数据.
		init_proto_head(cdn_forward_buf, sizeof(protocol_t) + sizeof(proto_cdn_speed_ip_t),
				proto_as_cdn_report_ip, 0, 0, 0);
		forward_ip = (proto_cdn_speed_ip_t*)(cdn_forward_buf + sizeof(protocol_t));
		forward_ip->ip = packet->record.m_cdn.cdn_ip;
		forward_ip->project_number = packet->project_number;
		forward_ip->speed = packet->record.m_cdn.speed;
		forward_ip->count = 1;
		for (k = 0; k < CDN_TIME_INTER; k++) {
			forward_ip->test_time = packet->test_time + k * 60 ;//add 60 secs
			send_data(cdn_forward_buf, sizeof(protocol_t) + sizeof(proto_cdn_speed_ip_t),
					proto_as_cdn_report_ip);
		}

		if (!find_client)
			return 0;

		init_proto_head(cdn_forward_buf, sizeof(protocol_t) + sizeof(proto_cdn_speed_area_t),
				proto_as_cdn_report_cityisp, 0, 0, 0);
		forward_area = (proto_cdn_speed_area_t*)(cdn_forward_buf + sizeof(protocol_t));
		forward_area->project_number = packet->project_number;
		forward_area->province_code = code_client.province_code;
		forward_area->city_code = code_client.city_code;
		memcpy(forward_ip_isp->isp, code_client.isp, ISP_LEN);
		forward_area->speed = packet->record.m_cdn.speed;
		forward_area->count = 1;
		for (k = 0; k < CDN_TIME_INTER; k++) {
			forward_area->test_time = packet->test_time + k * 60;//add 60 secs
			send_data(cdn_forward_buf, sizeof(protocol_t) + sizeof(proto_cdn_speed_area_t),
					proto_as_cdn_report_cityisp);
		}
		return 0;
	}

	//added by singku 2011-09-01 for cdn details forward ---start
	//cdn详情数据直接转发,不需要过滤speed=-1的数据。
    
	if (find_client) {
		init_proto_head(cdn_forward_buf, sizeof(protocol_t) + sizeof(proto_cdn_speed_ip_isp_t),
				proto_as_cdn_report_ip_isp, 0, 0, 0);
		forward_ip_isp = (proto_cdn_speed_ip_isp_t*)(cdn_forward_buf + sizeof(protocol_t));
		forward_ip_isp->project_number = packet->project_number;
		forward_ip_isp->test_time = packet->test_time;
		forward_ip_isp->ip = packet->record.m_cdn.cdn_ip;
		forward_ip_isp->province_id = code_client.province_code;
		forward_ip_isp->city_id = code_client.city_code;
		memcpy(forward_ip_isp->isp, code_client.isp, ISP_LEN);
		forward_ip_isp->speed = packet->record.m_cdn.speed;
		forward_ip_isp->count = 1;
		send_data(cdn_forward_buf, sizeof(protocol_t) + sizeof(proto_cdn_speed_ip_isp_t),
				proto_as_cdn_report_ip_isp);
	}
	//added by singku 2011-09-01 for cdn details forward ---end
    
	//如果send_cdn_ip_2_dbser线程要删除过期的某个cdn_ip,为了保证数据安全,必须等待其删除完毕
	pthread_spin_lock(&lock_cdn_ip);
	int proj = (packet->project_number-1) % max_project_number;
	cdn_ip_p = (cdn_speed_ip_t*)cdn_speed_ip_mmap[ proj ].mmap_p;
	cdn_area_p = (cdn_speed_area_t*)cdn_speed_area_mmap[ proj ].mmap_p;
	tmp_for_cdn_node = (cdn_speed_area_t*)cdn_speed_area_mmap[ proj ].mmap_p;

	//更新ip mmap
	uint32_t time_step;
    int pos;
	uint32_t tmp_speed = packet->record.m_cdn.speed / (1024); //KB
	uint32_t *offset = (uint32_t*)g_hash_table_lookup(cdn_hash_ip[proj], &packet->record.m_cdn.cdn_ip);
	if (offset == NULL) {
		if ((cdn_speed_ip_mmap[ proj ].records_num + 1) > MAX_IP_RECORD) {
			pthread_spin_unlock(&lock_cdn_ip);
			ERROR_RETURN(("ip records reach max number %u",MAX_IP_RECORD), 0);
		}

		if (g_ipDict.find(packet->record.m_cdn.cdn_ip, code_cdn, &isp_key) == false) {
			pthread_spin_unlock(&lock_cdn_ip);
			return 0;
		}
        if (code_cdn.province_code == 830000) {//国外
            pthread_spin_unlock(&lock_cdn_ip);
            return 0;
        }
		cdn_speed_ip_mmap[ proj ].records_num++;
		cdn_speed_ip_mmap[ proj ].mmap_head->records_num++;
        cdn_speed_ip_mmap[ proj ].ready_num++;
        cdn_speed_ip_mmap[ proj ].mmap_head->ready_num++;
		cdn_ip_p += cdn_speed_ip_mmap[ proj ].records_num - 1;
		cdn_ip_p->offset = cdn_speed_ip_mmap[ proj ].records_num - 1;
		cdn_ip_p->isp_key = isp_key;
		cdn_ip_p->step = 0;
		cdn_ip_p->ip = packet->record.m_cdn.cdn_ip;
		cdn_ip_p->project_number = packet->project_number;
		time_step = cdn_ip_p->step;
		cdn_ip_p->time[time_step] = packet->test_time;

        for (k = 0; k < CDN_TIME_INTER; k++) {
            pos = (time_step + k) % CDN_TIME_INTER;
            cdn_ip_p->speed[pos] = (speed_invalid == false) ? packet->record.m_cdn.speed : 0;
            cdn_ip_p->count[pos] = 1;//(speed_invlaid == false) ? 1 : 0;

		    //added by singku for speed distribution 2011-11-21
            //modify by tonyliu 2012-11-07
		    if (speed_invalid) {
		    	cdn_ip_p->speed_distribution[pos][0] = 1;
		    } else {
		    	if (tmp_speed < cdn_speed_dis[0]) {
		    		cdn_ip_p->speed_distribution[pos][1] = 1;
		    	} else if (tmp_speed < cdn_speed_dis[1]) {
		    		cdn_ip_p->speed_distribution[pos][2] = 1;
		    	} else if (tmp_speed < cdn_speed_dis[2]) {
		    		cdn_ip_p->speed_distribution[pos][3] = 1;
		    	} else if (tmp_speed < cdn_speed_dis[3]) {
		    		cdn_ip_p->speed_distribution[pos][4] = 1;
		    	} else {
		    		cdn_ip_p->speed_distribution[pos][5] = 1;
		    	}
		    }
		    //added by singku for speed distribution 2011-11-21
        }
		g_hash_table_insert(cdn_hash_ip[proj], &cdn_ip_p->ip, &cdn_ip_p->offset);
	}
	else {
		cdn_ip_p += *offset;
		time_step = cdn_ip_p->step;
		if (cdn_ip_p->count[time_step] == 0) {
			cdn_speed_ip_mmap[ proj ].ready_num++;
			cdn_speed_ip_mmap[ proj ].mmap_head->ready_num++;
		}
		cdn_ip_p->offset = *offset;
		cdn_ip_p->ip = packet->record.m_cdn.cdn_ip;
		cdn_ip_p->project_number = packet->project_number;
		cdn_ip_p->time[time_step] = max(cdn_ip_p->time[time_step], packet->test_time);

		for (k = 0; k < CDN_TIME_INTER; k++) {
            pos = (time_step + k) % CDN_TIME_INTER;
			cdn_ip_p->speed[pos] += (speed_invalid == false) ? packet->record.m_cdn.speed : 0;
            cdn_ip_p->count[pos] += 1;
            //if (cdn_ip_p->count[pos] == 0) {
            //    cdn_ip_p->count[pos] = 1;
            //} else {
			//    cdn_ip_p->count[pos] += (speed_invalid == false) ? 1 : 0;
		    //}

		    //added by singku for speed distribution 2011-11-21
            //modify by tonyliu 2012-11-07
		    if (speed_invalid) {
		    	cdn_ip_p->speed_distribution[pos][0] ++;
		    } else {
		    	if (tmp_speed < cdn_speed_dis[0]) {
		    		cdn_ip_p->speed_distribution[pos][1] ++;
		    	} else if (tmp_speed < cdn_speed_dis[1]) {
		    		cdn_ip_p->speed_distribution[pos][2] ++;
		    	} else if (tmp_speed < cdn_speed_dis[2]) {
		    		cdn_ip_p->speed_distribution[pos][3] ++;
		    	} else if (tmp_speed < cdn_speed_dis[3]) {
		    		cdn_ip_p->speed_distribution[pos][4] ++;
		    	} else {
		    		cdn_ip_p->speed_distribution[pos][5] ++;
		    	}
		    }
		    //added by singku for speed distribution 2011-11-21
        }
	}
	pthread_spin_unlock(&lock_cdn_ip);

	//更新area mmap
	if (!find_client)
		return 0;

	offset = (uint32_t*)g_hash_table_lookup(hash_cityisp, code_client.key);
	if (offset == NULL)
		return 0;
	else {
		cdn_area_p += *offset;
		time_step = cdn_area_p->step;
		if (cdn_area_p->count[time_step] == 0) {
			cdn_speed_area_mmap[ proj ].ready_num++;
			cdn_speed_area_mmap[ proj ].mmap_head->ready_num++;
		}
		cdn_area_p->project_number = packet->project_number;
		cdn_area_p->time[time_step] = max(packet->test_time, cdn_area_p->time[time_step]);

		for (k = 0; k < CDN_TIME_INTER; k++) {
            pos = (time_step + k) % CDN_TIME_INTER;
			cdn_area_p->speed[pos] += (speed_invalid == false) ? packet->record.m_cdn.speed : 0;
            cdn_area_p->count[pos] += 1;
            //if (cdn_area_p->count[pos] == 0) {
            //    cdn_area_p->count[pos] = 1;
            //} else {
			//    cdn_area_p->count[pos] += (speed_invalid == false) ? 1 : 0;
		    //}

		    //added by singku for speed distribution 2011-11-21
            //modify by tonyliu 2012-11-07
		    if (speed_invalid) {
		    	cdn_area_p->speed_distribution[pos][0] ++;
		    } else {
		    	if (tmp_speed < cdn_speed_dis[0]) {
		    		cdn_area_p->speed_distribution[pos][1] ++;
		    	} else if (tmp_speed < cdn_speed_dis[1]) {
		    		cdn_area_p->speed_distribution[pos][2] ++;
		    	} else if (tmp_speed < cdn_speed_dis[2]) {
		    		cdn_area_p->speed_distribution[pos][3] ++;
		    	} else if (tmp_speed < cdn_speed_dis[3]) {
		    		cdn_area_p->speed_distribution[pos][4] ++;
		    	} else {
		    		cdn_area_p->speed_distribution[pos][5] ++;
		    	}
		    }
		    //added by singku for speed distribution 2011-11-21
        }

	}

	return 0;
}
Beispiel #12
0
static int process_tmpfile(char *filepath)
{
	mmap_file_head_t tmp_head;
	int fd = open(filepath, O_RDWR);
	if (fd == -1) {
		ERROR_RETURN(("fail to open file %s", filepath), 0);
	}
	read(fd, &tmp_head, sizeof(mmap_file_head_t));
	if (memcmp(tmp_head.file_symbol, MMAP_FILE_SYMBOL, MMAP_FILE_SYMBOL_LEN) != 0) {
		close(fd);
		remove(filepath);
		ERROR_RETURN(("invalid mmap tmp file %s", filepath), 0);
	}
	if (tmp_head.records_num == 0 || tmp_head.ready_num == 0) {
		close(fd);
		remove(filepath);
		ERROR_RETURN(("ready or records equal 0 %s:records:%u,ready:%u",
				filepath, tmp_head.records_num, tmp_head.ready_num), 0);
	}
	if (tmp_head.records_num < tmp_head.ready_num) {
		close(fd);
		remove(filepath);
		ERROR_RETURN(("ready > records %s:records:%u,ready:%u",
				filepath, tmp_head.records_num, tmp_head.ready_num), 0);
	}
    
	lseek(fd, 0, SEEK_SET);//如果正常,则回到文件头
	uint32_t size;
	if (tmp_head.type == MMAP_TYPE_CDN_IP)
		size = cdn_mmap_size_ip;
	else if (tmp_head.type == MMAP_TYPE_CDN_AREA)
		size = cdn_mmap_size_area;
	else if (tmp_head.type == MMAP_TYPE_URL)
		size = url_mmap_size_page;
	else {
		close(fd);
		return 0;//other file
	}
	size += MMAP_FILE_HEAD_LEN;

	mmap_tmpfile_pmap = (char *)mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (mmap_tmpfile_pmap == (char *)-1) {
		close (fd);
		ERROR_RETURN(("fail to mmap %s", filepath), 0);
	}
	close(fd);
	//发送mmap的内容
	DEBUG_LOG("TMP MMAP TYPE:%02u,READY:%u,TAG:%u", tmp_head.type,tmp_head.ready_num, tmp_packet_tag);
    int ret_val;
	if (tmp_head.type == MMAP_TYPE_CDN_IP) {
		ret_val = send_cdn_ip_2_dbserver(mmap_tmpfile_pmap);
    }
	else if (tmp_head.type == MMAP_TYPE_CDN_AREA) {
        ret_val = send_cdn_area_2_dbserver(mmap_tmpfile_pmap);
    }
	else if (tmp_head.type == MMAP_TYPE_URL) {
		ret_val = send_url_page_2_dbserver(mmap_tmpfile_pmap);
	}

	munmap(mmap_tmpfile_pmap, size);
    
    if (ret_val == -1)
        ERROR_RETURN(("send mmap:file not complete %s", filepath) , -1);

	remove(filepath);
	return 0;
}
Beispiel #13
0
static int send_url_page_2_dbserver(char *mmap_p)
{
	mmap_file_head_t *file_head_p = (mmap_file_head_t*)mmap_p;
	url_test_t *url_page_p = (url_test_t*)(mmap_p + sizeof(mmap_file_head_t));
	uint8_t buf[BUF_NET_SEND_LEN];
	proto_url_test_fixed_t *buf_ptr;
	int len;
	uint32_t i;
	uint32_t send_count = 0;
	uint32_t ready = file_head_p->ready_num;
	int number;// = url_page_p->project_number;
	uint32_t packet_tag = tmp_packet_tag << SHIFT_BITS;

resend_url:
	ready -= send_count;
	send_count = 0;
	for (i = 0; i < file_head_p->records_num; i++) {
		if ((url_page_p + i)->count == 0)
			continue;
		if ((url_page_p + i)->v_count == 0) {
			file_head_p->ready_num --;
			continue;
		}

		/*start---added by singku for cache 11-07-27*/
		if (other_start == 1)
			update_cache(proto_cache_url_area, (void*)(url_page_p + i));
		/*end ----added by singku for cache 11-07-27*/

		//init protocol_head;
		number = ((url_page_p + i)->project_number -1) % max_project_number + 1;
		int vlen = (url_page_p + i)->v_count * sizeof((url_page_p + i)->vlist[0]);
		len = sizeof(protocol_t) + sizeof(proto_url_test_fixed_t) + vlen;
		init_proto_head(buf, len, proto_as_url_stat_page_time, (packet_tag + number), i, 0);
		DEBUG_LOG("SEND URL AREA PACKET___PROTO:%x,ID:%u,Number:%u,%s,Page:%u,v_count:%u,"
				"list:%u,%u,%u,%u,%u,%u,%u,%u,%u,%u",
				proto_as_url_stat_page_time,i,number, g_ipDict.m_ipmap[(url_page_p+i)->isp_key].isp,
				(url_page_p+i)->page_id,(url_page_p+i)->v_count,
				(url_page_p+i)->vlist[0],
				(url_page_p+i)->vlist[1],
				(url_page_p+i)->vlist[2],
				(url_page_p+i)->vlist[3],
				(url_page_p+i)->vlist[4],
				(url_page_p+i)->vlist[5],
				(url_page_p+i)->vlist[6],
				(url_page_p+i)->vlist[7],
				(url_page_p+i)->vlist[8],
				(url_page_p+i)->vlist[9]);

		buf_ptr = (proto_url_test_fixed_t*)(buf + sizeof(protocol_t));
		buf_ptr->project_number = (url_page_p + i)->project_number;
		buf_ptr->page_id = (url_page_p + i)->page_id;
		buf_ptr->provice_code = g_ipDict.m_ipmap[(url_page_p + i)->isp_key].province_code;
		buf_ptr->city_code = g_ipDict.m_ipmap[(url_page_p + i)->isp_key].city_code;
		buf_ptr->isp_id = g_ipDict.m_ipmap[(url_page_p + i)->isp_key].isp_id;
		memcpy(buf_ptr->isp, g_ipDict.m_ipmap[(url_page_p + i)->isp_key].isp, ISP_LEN);
		buf_ptr->test_time = (url_page_p + i)->test_time;
		buf_ptr->count = (url_page_p + i)->count;
		buf_ptr->v_count = (url_page_p + i)->v_count;
		memcpy(buf + sizeof(protocol_t) + sizeof(proto_url_test_fixed_t), (url_page_p + i)->vlist, vlen);
		if (send_data(buf, len, proto_as_url_stat_page_time) == -1)
			return -1;

		send_count ++;
		if (send_count == ready)
			break;
	}

	if (send_count == 0)
		ERROR_RETURN(("SEND COUNT == 0:map_tag:%u,type:URL PAGE", tmp_packet_tag), 0);
	if (wait_all_tmpdata_ok(mmap_p) == -1) {
		ERROR_LOG("URL PAGE:WAIT RET PACKETS TIME OUT");
		goto resend_url;
	}

	return 0;
}
Beispiel #14
0
static int send_cdn_area_2_dbserver(char *mmap_p)
{
	mmap_file_head_t *file_head_p = (mmap_file_head_t*)mmap_p;
	cdn_speed_area_t *cdn_area_p = (cdn_speed_area_t*)(mmap_p + sizeof(mmap_file_head_t));
	uint8_t buf[BUF_NET_SEND_LEN];
	proto_cdn_speed_area_t *buf_ptr;
	int len;
	uint32_t i;
	uint32_t send_count=0;
	uint32_t ready = file_head_p->ready_num;
	int number;// = cdn_area_p->project_number;
	uint32_t packet_tag = tmp_packet_tag << SHIFT_BITS;

resend_cdnarea:
	ready -= send_count;
	send_count = 0;
	for (i = 0; i < file_head_p->records_num; i++) {

		(cdn_area_p + i)->t_time = (cdn_area_p + i)->time[(cdn_area_p + i)->step];
		(cdn_area_p + i)->t_speed = (cdn_area_p + i)->speed[(cdn_area_p + i)->step];
		(cdn_area_p + i)->t_count = (cdn_area_p + i)->count[(cdn_area_p + i)->step];


		if ((cdn_area_p + i)->t_count == 0)
			continue;

		/*start---added by singku for cache 11-07-26*/
		if (other_start == 1)
        {
            cdn_speed_area_t *p_cdn_area = cdn_area_p + i;
            INFO_LOG("AAAA:time[%u] speed[%u] count[%u]", p_cdn_area->t_time, p_cdn_area->t_speed, p_cdn_area->t_count);
            int m = 0;
            for (m = 0; m < 6; m++)
            {
                INFO_LOG("AAAA:dis[%d]: %u", m, p_cdn_area->speed_distribution[(cdn_area_p + i)->step][m]);
            }

			update_cache(proto_cache_cdn_area, (void*)(cdn_area_p + i));
        }
		/*end ----added by singku for cache 11-07-26*/

		//init protocol_head;
		number = ((cdn_area_p + i)->project_number -1) % max_project_number + 1;
		len = sizeof(protocol_t) + sizeof(proto_cdn_speed_area_t);

		init_proto_head(buf, len, proto_as_cdn_report_cityisp, (packet_tag + number), i, 0);
		DEBUG_LOG("SEND CDN AREA PACKET___PROTO:%x,ID:%u,Number:%u,%s,Time:%u,Speed:%u,Count:%u",
				proto_as_cdn_report_cityisp,i,(cdn_area_p+i)->project_number,
				g_ipDict.m_ipmap[(cdn_area_p+i)->isp_key].isp, (cdn_area_p+i)->t_time,
				(cdn_area_p+i)->t_speed/(cdn_area_p+i)->t_count,
				(cdn_area_p+i)->t_count);
		buf_ptr = (proto_cdn_speed_area_t*)(buf + sizeof(protocol_t));
		buf_ptr->project_number = (cdn_area_p + i)->project_number;
		buf_ptr->province_code = g_ipDict.m_ipmap[(cdn_area_p+i)->isp_key].province_code;
		buf_ptr->city_code = g_ipDict.m_ipmap[(cdn_area_p+i)->isp_key].city_code;
		memcpy(buf_ptr->isp, g_ipDict.m_ipmap[(cdn_area_p+i)->isp_key].isp, ISP_LEN);
		buf_ptr->test_time = (cdn_area_p + i)->t_time;
		buf_ptr->speed = (cdn_area_p + i)->t_speed;
		buf_ptr->count = (cdn_area_p + i)->t_count;

		if (send_data(buf, len, proto_as_cdn_report_cityisp) == -1)
			return -1;

		send_count ++;
		if (send_count == ready)
			break;
	}

	if (send_count == 0)
		ERROR_RETURN(("SEND COUNT == 0:map_tag:%u,type:CDN AREA", tmp_packet_tag), 0);
	if (wait_all_tmpdata_ok(mmap_p) == -1) {
		ERROR_LOG("CDN AREA:WAIT RET PACKETS TIME OUT");
		goto resend_cdnarea;
	}

	return 0;
}
Beispiel #15
0
/****************  main  *******************/
int main(int argc, char** argv)
{
  PGconn* pgConn;
  PGresult* result;
  psqlCopy_t pCopy;
  char* TestTable = "TestsqlCopy";
  char col_vc[40] = "This is \n\r column vc[40] 123456789\r";
  char* col_text;
  char* DataBuf;
  int datasize;
  char sql[2048];
  int NumColumns = 3;
  int CopyBufSize;
  int RowsToTest;
  int NumTextBytes;
  int RowNum;
  clock_t StartTime, EndTime;
  char* DBConfFile = NULL;  /* use default Db.conf */
  char* ErrorBuf;

  if (argc != 4)
  {
    printf("Usage: %s RowsToTest NumTextBytes CopyDataBufferSize\n", argv[0]);
    exit(-1);
  }

  /* first argument is the number of rows to test, 
   * the second is the number of bytes to use for col_text
   * third is the Copy data buffer size
   */
  RowsToTest = atoi(argv[1]);
  NumTextBytes = atoi(argv[2]);
  CopyBufSize = atoi(argv[3]);

  /* Populate test data */
  col_text = GetTextCol(NumTextBytes);
  datasize = NumTextBytes + 8 + 40 + 1;
  DataBuf = calloc(datasize, sizeof(char));
  if (!DataBuf)
  {
    ERROR_RETURN("Allocating test data buffer failed.")
    exit(-2);
  }

  pgConn = fo_dbconnect(DBConfFile, &ErrorBuf);

  /* Create a test table to populate */
  snprintf(sql, sizeof(sql), "create table %s (col_int integer, col_text text, col_vc varchar(40))", TestTable);
  result = PQexec(pgConn, sql);
  fo_checkPQcommand(pgConn, result, sql, __FILE__, __LINE__);

  /* Start timer */
  StartTime = clock();

  /* Create the pCopy */
  pCopy = fo_sqlCopyCreate(pgConn, TestTable, CopyBufSize, NumColumns,
    "col_int", "col_text", "col_vc");
  if (!pCopy) exit(1);  /* CopyCreate prints errors to stdout */

  /* Add data */
  for (RowNum = 0; RowNum < RowsToTest; RowNum++)
  {
    snprintf(DataBuf, datasize, "%d\t%s\t%s\n", RowNum, col_text, col_vc);
    fo_sqlCopyAdd(pCopy, DataBuf);
  }
  free(col_text);

  /* Destroy - flushes remaining data and frees */
  fo_sqlCopyDestroy(pCopy, 1);

  /* Print run time for the load (whole Create/Add/Destroy cycle). */
  EndTime = clock();
  printf("%.6f Seconds to load.\n", ((double) (EndTime - StartTime)) / CLOCKS_PER_SEC);

  /* Verify that the right number of records were loaded */
  snprintf(sql, sizeof(sql), "select count(*) from %s", TestTable);
  result = PQexec(pgConn, sql);
  fo_checkPQresult(pgConn, result, sql, __FILE__, __LINE__);
  printf("%d records inserted, %d expected\n",
    atoi(PQgetvalue(result, 0, 0)),
    RowsToTest);
  PQclear(result);

  /* Remove the test table */
/*
  snprintf(sql, sizeof(sql), "drop table %s", TestTable);
  result = PQexec(pgConn, sql);
  fo_checkPQcommand(pgConn, result, sql, __FILE__, __LINE__);
*/

  PQfinish(pgConn);
  return (0);
}
Beispiel #16
0
int cmd_compare (int argc, const char** argv)
{
  struct descriptor_d din;
  struct descriptor_d dout;
  int result = 0;
  ssize_t cbCompare = 0;
  size_t cbTotal = 0;
  int count = 1;

  if (argc >= 3 && strcmp (argv[1], "-c") == 0) {
    count = simple_strtoul (argv[2], NULL, 0);
    argc -= 2;
    argv += 2;
  }

  if (count <= 0)
    ERROR_RETURN (ERROR_PARAM, "count must be >0");

  if (argc < 3)
    return ERROR_PARAM;

  if (   (result = parse_descriptor (argv[1], &din))
      || (result = open_descriptor (&din))) {
    printf ("Unable to open '%s'\n", argv[1]);
    goto fail_early;
  }

  if (   (result = parse_descriptor (argv[2], &dout))
      || (result = open_descriptor (&din))) {
    printf ("Unable to open '%s'\n", argv[2]);
    goto fail;
  }

  if (!din.driver->read || !dout.driver->read) {
    result = ERROR_UNSUPPORTED;
    goto fail;
  }

  /* Make lengths the same */
  cbTotal = din.length;
  if (dout.length && dout.length < din.length)
    cbTotal = dout.length;
  din.length = cbTotal;
  dout.length = cbTotal;

  while (cbCompare < cbTotal && count) {
    char __aligned rgbIn [512];
    char __aligned rgbOut[512];
    ssize_t cbIn;
    ssize_t cbOut;
    ssize_t cb;

    cbIn  = din.driver ->read (&din,  rgbIn,  sizeof (rgbIn));
    cbOut = dout.driver->read (&dout, rgbOut, sizeof (rgbOut));

    if (cbIn != cbOut) {
      printf ("\rregions not the same length\n");
      result = ERROR_FALSE;
      goto fail;
    }

    for (cb = 0; cb < cbIn; ++cb) {
      if (rgbIn[cb] != rgbOut[cb]) {
	printf ("\rregions differ 0x%02x != 0x%02x at %d (0x%x)\n",
		rgbIn[cb], rgbOut[cb], cb + cbCompare, cb + cbCompare);
	result = ERROR_FALSE;
	if (--count == 0)
	  goto fail;
      }
    }
    cbCompare += cbIn;
  }

  if (result == 0)
    printf ("\r%d bytes the same\n", cbCompare);

 fail:
  close_descriptor (&din);
  close_descriptor (&dout);
 fail_early:

  return result;
}
Beispiel #17
0
int main(int argc, char **argv)
{
   int i , PAPI_event;
   int EventSet = PAPI_NULL;
   unsigned short *profbuf;
   unsigned short *profbuf2;
   unsigned short *profbuf3;
   unsigned long length;
   caddr_t start, end;
   long long values[2];
   const PAPI_exe_info_t *prginfo = NULL;
   PAPI_sprofil_t sprof[3];
   int retval;

   /* initializaion */
   if ((retval = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT)
   {
      printf("Library initialization error! \n");
      exit(1);
   }

   if ((prginfo = PAPI_get_executable_info()) == NULL) 
      ERROR_RETURN(1);

   start = prginfo->address_info.text_start;
   end = prginfo->address_info.text_end;
   length = (end - start)/sizeof(unsigned short) * sizeof(unsigned short);
   printf("start= %p  end =%p \n", start, end);

   profbuf = (unsigned short *) malloc(length);
   if (profbuf == NULL) 
      ERROR_RETURN(PAPI_ESYS);

   memset(profbuf, 0x00, length );

   profbuf2 = (unsigned short *) malloc(length);
   if (profbuf2 == NULL) 
      ERROR_RETURN(PAPI_ESYS);

   memset(profbuf2, 0x00, length );

   profbuf3 = (unsigned short *) malloc(1 * sizeof(unsigned short));
   if (profbuf3 == NULL) 
      ERROR_RETURN(PAPI_ESYS);

   memset(profbuf3, 0x00, 1 * sizeof(unsigned short));

   /* First half */
   sprof[0].pr_base = profbuf;
   sprof[0].pr_size = length / 2;
   sprof[0].pr_off = DO_FLOPS2;
   fprintf(stderr, "do_flops is at %p %lx\n", &do_flops2, strtoul(sprof[0].pr_off,NULL,0));

   sprof[0].pr_scale = 65536;  /* constant needed by PAPI_sprofil */
   /* Second half */
   sprof[1].pr_base = profbuf2;
   sprof[1].pr_size = length / 2;
   sprof[1].pr_off = DO_FLOPS1;
   fprintf(stderr, "do_flops1 is at %p %lx\n", &do_flops1, strtoul(sprof[1].pr_off,NULL,0));
   sprof[1].pr_scale = 65536; /* constant needed by PAPI_sprofil */

   /* Overflow bin */
   sprof[2].pr_base = profbuf3;
   sprof[2].pr_size = 1;
   sprof[2].pr_off = 0;
   sprof[2].pr_scale = 0x2;  /* constant needed by PAPI_sprofil */

   /* Creating the eventset */
   if ( (retval = PAPI_create_eventset(&EventSet)) != PAPI_OK)
      ERROR_RETURN(retval);

   PAPI_event = PAPI_TOT_CYC;
   /* Add Total Instructions Executed to our EventSet */
   if ( (retval = PAPI_add_event(EventSet, PAPI_event)) != PAPI_OK)
      ERROR_RETURN(retval);

   /* Add Total Instructions Executed to our EventSet */
   if ( (retval = PAPI_add_event(EventSet, PAPI_TOT_INS)) != PAPI_OK)
      ERROR_RETURN(retval);

   /* set profile flag */
   if ((retval = PAPI_sprofil(sprof, 3, EventSet, PAPI_event, THRESHOLD,
                              PAPI_PROFIL_POSIX)) != PAPI_OK)
      ERROR_RETURN(retval);

   if ((retval = PAPI_start(EventSet)) != PAPI_OK)
      ERROR_RETURN(retval);

   do_both(NUM_ITERS);

   if ((retval = PAPI_stop(EventSet, values)) != PAPI_OK)
      ERROR_RETURN(retval);

   /* to clear the profile flag before removing the events */
   if ((retval = PAPI_sprofil(sprof, 3, EventSet, PAPI_event, 0,
                              PAPI_PROFIL_POSIX)) != PAPI_OK)
      ERROR_RETURN(retval);

   /* free the resources hold by PAPI */
   PAPI_shutdown();

   printf("Test case: PAPI_sprofil()\n");
   printf("---------Buffer 1--------\n");
   for (i = 0; i < length / 2; i++) 
   {
      if (profbuf[i])
	printf("%#lx\t%d\n", strtoul(DO_FLOPS2,NULL,0) + 2 * i, profbuf[i]);
   }
   printf("---------Buffer 2--------\n");
   for (i = 0; i < length / 2; i++) 
   {
      if (profbuf2[i])
	printf("%#lx\t%d\n", strtoul(DO_FLOPS1,NULL,0) + 2 * i, profbuf2[i]);
   }
   printf("-------------------------\n");
   printf("%u samples fell outside the regions.\n", *profbuf3);

   exit(0);
}
static int load_conf()
{
	char *str;
	int	 port;
	int tmp_max_project_number;
	int tmp_max_page;
	//int tmp_accepted_proj;
	int tmp_upper_bound;
	int tmp_max_idc;

	str = config_get_strval("dbserver_ip");
	if (str != NULL && is_legal_ip( (const char *)str ))
		strncpy(dbserver_ip, str, sizeof(dbserver_ip));
	else
		ERROR_RETURN(("can't find legal dbserver ip\t"), -1);

	strncpy((char*)db_server_set[0].ip, dbserver_ip, sizeof(dbserver_ip));

	str = config_get_strval("bind_ip");
	if (str != NULL && is_legal_ip( (const char *)str ))
		strncpy(bind_ip, str, sizeof(bind_ip));
	else
		ERROR_RETURN(("can't find legal bind ip\t"), -1);

	port = config_get_intval("dbserver_port", dbserver_port);
	if (is_legal_port(port))
		dbserver_port = port;
	else
		ERROR_RETURN(("can't find legal dbserver port\t"), -1);

	db_server_set[0].port = dbserver_port;

	port = config_get_intval("bind_port", bind_port);
	if (is_legal_port(port))
		bind_port = port;
	else
		ERROR_RETURN(("can't find legal bind port\t"), -1);

	tmp_max_project_number = config_get_intval("max_project_number", max_project_number);
	if (tmp_max_project_number > 0 && tmp_max_project_number <= max_project_number)
		max_project_number = tmp_max_project_number;
	else
		ERROR_RETURN(("max_project_number is illegal, max value is:%u\t",max_project_number), -1);

	tmp_max_page = config_get_intval("max_page_per_proj", max_page_per_proj);
	if (tmp_max_page > 0 && tmp_max_page <= max_page_per_proj)
		max_page_per_proj = tmp_max_page;
	else
		ERROR_RETURN(("max_page_per_proj is illegal, max value is:%u\t",max_page_per_proj), -1);

	tmp_upper_bound = config_get_intval("delay_upper_bound", delay_upper_bound);
	if (tmp_upper_bound > 0 && tmp_upper_bound <= delay_upper_bound)
		delay_upper_bound = tmp_upper_bound;
	else
		ERROR_RETURN(("delay_upper_bound is illegal, max value is:%u\t",delay_upper_bound), -1);

	tmp_max_idc = config_get_intval("max_idc_number", max_idc_number);
	if (tmp_max_idc > 0 && tmp_max_idc <= max_idc_number)
		max_idc_number = tmp_max_idc;

	uint32_t tmp_max_cdn_speed;
	tmp_max_cdn_speed = config_get_intval("max_cdn_speed", cdn_max_speed);
	if (tmp_max_cdn_speed > 1024 && tmp_max_cdn_speed <= cdn_max_speed)
		cdn_max_speed = tmp_max_cdn_speed;


	str = config_get_strval("link_ip_config_file");
	if (str != NULL )
		strncpy(link_ip_config_file, str, sizeof(link_ip_config_file));
	else
		ERROR_RETURN(("can't find link_ip_config_file\t"), -1);

	int tmp_remove_or_rename = config_get_intval("remove_or_rename", remove_or_rename);
	if (tmp_remove_or_rename == REMOVE_IDC_FILE || tmp_remove_or_rename == RENAME_IDC_FILE)
		remove_or_rename = tmp_remove_or_rename;

	if (remove_or_rename == RENAME_IDC_FILE) {
		str = config_get_strval("idc_rename_dirpath");
		if (str != NULL)
			strncpy(idc_rename_dirpath, str, sizeof(idc_rename_dirpath));
		else
			ERROR_RETURN(("can't find idc_file_dirpath\t"), -1);
	}

	str = config_get_strval("idc_file_dirpath");
	if (str != NULL)
		strncpy(idc_file_dirpath, str, sizeof(idc_file_dirpath));
	else
		ERROR_RETURN(("can't find idc_file_dirpath\t"), -1);

	str = config_get_strval("mmap_tmpfile_dirpath");
	if (str != NULL)
		strncpy(mmap_tmpfile_dirpath, str, sizeof(mmap_tmpfile_dirpath));
	else
		ERROR_RETURN(("can't find mmap_tmpfile_dirpath\t"), -1);


	str = config_get_strval("idc_mmap_file_dirpath");
	if (str != NULL)
		strncpy(idc_mmap_file_dirpath, str, sizeof(idc_mmap_file_dirpath));
	else
		ERROR_RETURN(("can't find idc_mmap_file_dirpath\t"), -1);

	str = config_get_strval("cdn_mmap_file_dirpath");
	if (str != NULL)
		strncpy(cdn_mmap_file_dirpath, str, sizeof(cdn_mmap_file_dirpath));
	else
		ERROR_RETURN(("can't find cdn_mmap_file_dirpath\t"), -1);

	str = config_get_strval("url_mmap_file_dirpath");
	if (str != NULL)
		strncpy(url_mmap_file_dirpath, str, sizeof(url_mmap_file_dirpath));
	else
		ERROR_RETURN(("can't find url_mmap_file_dirpath\t"), -1);

    //add by singku for ignoring some projects
    str = config_get_strval("ignore_project");
	if (str != NULL) {
        uint32_t i;
        while(str != NULL) {
            i = strtoul(str, NULL, 10);
            if (i == 0 || i == ULONG_MAX) {
                ERROR_LOG("bad config file: 'ignore_project'!\n");
                break;
            }
            ignore_project[ i% MAX_PROJECT_NUMBER] = 1;
            str = strchr(str, ',');
            if (str == NULL)
                break;
            str += 1;
        }
    }

	return 0;
}
Beispiel #19
0
/* @breif add item by use skill
 */
int get_item_by_skill_cmd(sprite_t *p, const uint8_t *body, int bodylen)
{
	CHECK_VALID_ID(p->id);
	/*pet id, skill type, itemid*/
	CHECK_BODY_LEN(bodylen, 12);

	if (p->followed == NULL) {
			ERROR_RETURN(("not followed lamu %u", p->id), -1);
	}

	uint32_t petid, skill_type, itemid;
	int j = 0;
	UNPKG_UINT32(body, petid, j);
	UNPKG_UINT32(body, skill_type, j);
	if ((skill_type > MAX_SKILL_NUM) || (skill_type < 1) || (skill_items[skill_type - 1].id ==0)) {
		ERROR_RETURN(("skill type wrong %u %u %u", p->id, skill_type, MAX_SKILL_NUM), -1);
	}
	UNPKG_UINT32(body, itemid, j);
	int item_skill_type = 0;
	if (!check_itemid(p, itemid, skill_type, &item_skill_type)) {
		ERROR_RETURN(("wrong itemid %u %u %u %u", p->id, skill_type, itemid, item_skill_type), -1);
	}
	/*ID号为零直接返回*/
	if (itemid == 0) {
		int i = sizeof(protocol_t);
		PKG_UINT32(msg, 0, i);
		PKG_UINT32(msg, p->followed->skill_value, i);
		init_proto_head(msg, p->waitcmd, i);
		return  send_to_self(p, msg, i, 1);
	}

	/*save item id, add change value, skill type*/
	*(uint32_t *)(p->session) = itemid;
	*(uint32_t *)(p->session + 8) = skill_type;
	/*check if have this skill, 126 map not check*/
	uint32_t not_check = (p->tiles->id == 126 && itemid == 190591)
						|| (p->tiles->id == 130 && itemid == 190611)
						|| (p->tiles->id == 134 && itemid == 190625);


	if (!not_check) {
		/*lamu should do action*/
		if (p->lamu_action == 0) {
			DEBUG_LOG("lamu action zero %u", p->id);
			return send_to_self_error(p, p->waitcmd, -ERR_action_have_fini, 1);
		}
		if (!check_skill(p, skill_type)) {
			DEBUG_LOG("have not this skill %u %u", p->id, skill_type);
			return send_to_self_error(p, p->waitcmd, -ERR_lahm_have_not_this_skill, 1);
		}
	}
	uint32_t day_limit = 0;
	if (ISVIP(p->flag)) {
		day_limit = skill_items[item_skill_type - 1].vip_limit;
	} else {
		day_limit = skill_items[item_skill_type -1].pl_limit;
	}

	uint32_t db_buf[7];
	db_buf[0] = item_skill_type;
	db_buf[1] = itemid;
	db_buf[2] = day_limit;
	db_buf[3] = p->followed->id;
	if (check_skill(p, skill_type)) {
		int add_change = skill_items[skill_type - 1].add_change;
		if (PET_IS_SUPER_LAHM(p->followed)) {
			add_change *= 2;
		}
		db_buf[4] = add_change;
		db_buf[5] = get_day_limit(p->followed);
		*(uint32_t *)(p->session + 4) = add_change;
	} else {
		*(uint32_t *)(p->session + 4) = 0;
		db_buf[4] = 0;
		db_buf[5] = 0;
	}
	db_buf[6] = 0;
	return send_request_to_db(SVR_PROTO_GET_ITEM_BY_USER_SKILL, p, sizeof(db_buf), db_buf, p->id);
}
static int load_ip()
{
	if (!g_ipDict.init("ipdict.dat.all_over_the_world"))	//加载IP库到g_ipDict的私有成员m_ipmap中
		ERROR_RETURN(("can not open \"ipdict.dat.all_over_the_world\""), -1);
	return 0;
}
Beispiel #21
0
int CreatureInfoMgr::LoadCreatureInfo()
{
	int ret = 0;
	xmlDocPtr doc;
	xmlNodePtr root;
	xmlNodePtr nodeCreature;
	int creatureCount = 0;
	char file[] = "./conf/angelfight/monsterinfo.xml";

	doc = xmlParseFile(file);
	if (!doc)
	{
		ERROR_RETURN( ( "CreatureInfoMgr::LoadCreatureInfo() Open [%s] Failed", file ), -1 );
	}

	root = xmlDocGetRootElement(doc);
	if ( !root )
	{
		ERROR_LOG("xmlDocGetRootElement error");
		ret = -1;
		goto exit;
	}
	//怪物总数
	DECODE_XML_PROP_INT( creatureCount, root, "Count" );
	if( creatureCount <= 0 )
	{
		goto exit;
	}

	m_vecCreatureInfo.clear();
	m_vecCreatureInfo.reserve(creatureCount);

	//获取子节点
	nodeCreature= root->xmlChildrenNode;
	while( nodeCreature )
	{
		CreatureInfo* pCreateure = NULL;
		if ( 0 == xmlStrcmp( nodeCreature->name, BAD_CAST"Monster" ) )
		{
			pCreateure = new CreatureInfo();
			pCreateure->m_nCreatureID = m_vecCreatureInfo.size();
			m_vecCreatureInfo.push_back(pCreateure);

			xmlChar* str;

			int ID;

			DECODE_XML_PROP_INT( ID, nodeCreature, "ID" );
			if( ID != pCreateure->m_nCreatureID )
			{
				ERROR_LOG( "Creature ID Invalid The Value is:[%d] Expect:[%u]", ID, pCreateure->m_nCreatureID );
			}

			str = xmlGetProp( nodeCreature, BAD_CAST"Level" );
			pCreateure->XmlSetLevel( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Str" );
			pCreateure->XmlSetStr( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Int" );
			pCreateure->XmlSetInt( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Hab" );
			pCreateure->XmlSetHabitus( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Ali" );
			pCreateure->XmlSetAgile( (char*)str );
			xmlFree(str);

			str = xmlGetProp( nodeCreature, BAD_CAST"Atk" );
			pCreateure->XmlSetAtk( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Aspd" );
			pCreateure->XmlSetAspd( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Evad" );
			pCreateure->XmlSetEvad( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Block" );
			pCreateure->XmlSetBlock( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Crit" );
			pCreateure->XmlSetCrit( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Hit" );
			pCreateure->XmlSetHit( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Combo" );
			pCreateure->XmlSetCombo( (char*)str );
			xmlFree(str);
			str = xmlGetProp( nodeCreature, BAD_CAST"Def" );
			pCreateure->XmlSetDef( (char*)str );
			xmlFree(str);

			str = xmlGetProp( nodeCreature, BAD_CAST"IsBoss" );
			pCreateure->XmlSetIsBoss( (char*)str );
			xmlFree(str);

			xmlNodePtr child = nodeCreature->xmlChildrenNode;
			while( child )
			{
				if( 0 == xmlStrcmp( child->name, BAD_CAST"Skill" ) )
				{
					str = xmlGetProp( child, BAD_CAST"ID" );
					pCreateure->XmlAddSkill( (char*)str );
				}
				else if( 0 == xmlStrcmp( child->name, BAD_CAST"Drop" ) )
				{
					str = xmlGetProp( child, BAD_CAST"ID" );
					pCreateure->XmlAddItem( (char*)str );
				}
				child = child->next;
			}
		}
		nodeCreature = nodeCreature->next;
	}
exit:
	xmlFreeDoc(doc);

	DEBUG_LOG( "Load Creature Info Over Creature Size Is:[%lu]", m_vecCreatureInfo.size() );
	return ret;
}
static int create_mmap(char *path, uint32_t mmap_size, my_mmap_t *a_mmap)
{
	//若mmap文件是新建立的,则flag置1,如为0,则上层函数根据mmap中的数据初始化hash表
	int fd = open(path, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	if (fd == -1) {
		ERROR_RETURN(("mmap: fail to open file %s", path), -1);
	}
	long fsize = lseek(fd, 0, SEEK_END);
	char zero[1024];
	memset(zero, 0x0,1024);
	if (fsize == 0) {
		//DEBUG_LOG("NEW MMAPFILE");
		ftruncate(fd, mmap_size + MMAP_FILE_HEAD_LEN);
		write(fd, MMAP_FILE_SYMBOL, MMAP_FILE_SYMBOL_LEN);
		write(fd, &zero, MMAP_FILE_RECORD_LEN + MMAP_FILE_READY_LEN);
		write(fd, &a_mmap->type, MMAP_FILE_TYPE_LEN);
		write(fd, &zero, MMAP_FILE_KEY_LEN + MMAP_FILE_VALUE_LEN + MMAP_FILE_LATEST_LEN);
		a_mmap->records_num = 0;
		a_mmap->ready_num = 0;
		a_mmap->key = 0;
		a_mmap->value = 0;
		a_mmap->latest_time = 0;
	}
	else {
		//DEBUG_LOG("VALID MMAPFILE");
		lseek(fd, 0, SEEK_SET );//如果不是新文件,则回到文件头并读取头部,以判断文件的正确性
		read(fd, &mmap_file_head, sizeof(mmap_file_head_t));
		if ( memcmp(mmap_file_head.file_symbol, MMAP_FILE_SYMBOL, MMAP_FILE_SYMBOL_LEN) == 0
				&& mmap_file_head.type == a_mmap->type) {
			a_mmap->records_num = mmap_file_head.records_num;
			a_mmap->ready_num = mmap_file_head.ready_num;
			a_mmap->key = mmap_file_head.key;
			a_mmap->value = mmap_file_head.value;
			a_mmap->latest_time = mmap_file_head.latest_time;
		}
		else {
			//DEBUG_LOG("INVALID MMAPFILE");
			lseek(fd, 0, SEEK_SET );//如果不是正确的mmap文件,则重置这个文件.
			ftruncate(fd, mmap_size + MMAP_FILE_HEAD_LEN);
			write(fd, MMAP_FILE_SYMBOL, MMAP_FILE_SYMBOL_LEN);
			write(fd, &zero, MMAP_FILE_RECORD_LEN + MMAP_FILE_READY_LEN);
			write(fd, &a_mmap->type, sizeof(a_mmap->type));
			write(fd, &zero, MMAP_FILE_KEY_LEN + MMAP_FILE_VALUE_LEN + MMAP_FILE_LATEST_LEN);
			a_mmap->records_num	= 0;
			a_mmap->ready_num = 0;
			a_mmap->key = 0;
			a_mmap->value = 0;
			a_mmap->latest_time = 0;
		}
	}
	char* pmap = (char *)mmap(0, MMAP_FILE_HEAD_LEN + mmap_size,
								PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	//msync(pmap, MMAP_FILE_HEAD_LEN + mmap_size, MS_SYNC);
	if(pmap == (char *)-1) {
            close (fd);
            ERROR_RETURN(("mmap: fail to mmap %s", path), -1);
	}
	a_mmap->mmap_head = (mmap_file_head_t*)pmap;
	a_mmap->mmap_p = pmap + MMAP_FILE_HEAD_LEN;
	close(fd);

	return 0;
}
static void run(
  const gchar *     name,
  gint              nparams,
	const GimpParam * param,
	gint *            nreturn_vals,
	GimpParam **      return_vals)
{
  static GimpParam values[2];   /* Gimp return values. !!! Allow 2: status and error message. */
  TGimpAdapterParameters pluginParameters;
  TImageSynthParameters engineParameters;
  
  GimpDrawable *drawable = NULL;
  GimpDrawable *corpus_drawable = NULL; 
  GimpDrawable *map_in_drawable= NULL; 
  GimpDrawable *map_out_drawable= NULL; 
  gboolean ok, with_map;
  
  /* 
  Local copies of pixmaps (not using gimp regions.) 
  2-D arrays of Pixel, addressable by Coordinates (Point).
  c++: static Bitmap<Pixelel>
  */
  Map targetMap;
  Map corpusMap;
  Map targetMaskMap;
  Map corpusMaskMap;
  
  int cancelFlag = 0;
  
  #ifdef SYNTH_THREADED
  // This is as early as it can be called.  Not sure it needs to be called.  See later call to it.
  // Call it early since calls to gdk, gtk might require this?
  g_thread_init(NULL);
  #endif

  #ifdef DEBUG
  gimp_message_set_handler(1); // To console instead of GUI
  start_time = clock();
  #endif
  
  // internationalization i18n
  // Note these constants are defined in the build environment.
  /*  Initialize i18n support  */
#if defined(G_OS_WIN32)
  bindtextdomain (GETTEXT_PACKAGE, gimp_locale_directory());
#else
  bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
#endif
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif
  textdomain (GETTEXT_PACKAGE);

  *nreturn_vals = 1;
  *return_vals = values;
  values[0].type = GIMP_PDB_STATUS;
  values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR; /* Unless everything succeeds. */
  
  drawable = gimp_drawable_get(param[2].data.d_drawable);

  /* Check image type (could be called non-interactive) */
  if (!gimp_drawable_is_rgb(drawable->drawable_id) &&
      !gimp_drawable_is_gray(drawable->drawable_id)) 
  {
    ERROR_RETURN(_("Incompatible image mode."));
  }


  /* Deal with run mode */
  ok = FALSE;
  switch(param[0].data.d_int32) 
  {
    case GIMP_RUN_INTERACTIVE :
      ok = get_last_parameters(&pluginParameters,drawable->drawable_id, RESYNTH_ENGINE_PDB_NAME);
      gimp_message("Resynthesizer engine should not be called interactively");
      /* But keep going with last (or default) parameters, really no harm. */
      break;
    case GIMP_RUN_NONINTERACTIVE :
      ok = get_parameters_from_list(&pluginParameters, nparams, param); 
      break;
    case GIMP_RUN_WITH_LAST_VALS :
      ok = get_last_parameters(&pluginParameters,drawable->drawable_id, RESYNTH_ENGINE_PDB_NAME); 
      break;
  }

  if (!ok) 
  {
    ERROR_RETURN(_("Resynthesizer failed to get parameters."));
  }
  
  /* Limit neighbours parameter to size allocated. */
  if (pluginParameters.neighbours > IMAGE_SYNTH_MAX_NEIGHBORS )
    pluginParameters.neighbours = IMAGE_SYNTH_MAX_NEIGHBORS;
  
  corpus_drawable = gimp_drawable_get(pluginParameters.corpus_id);
  
  /* The target and corpus must have the same base type.
  In earlier version, they must have the same bpp.
  But now we don't compare the alphas, so they can differ in presence of alpha.
  */
  if (! equal_basetypes(drawable, corpus_drawable) )
  {
    ERROR_RETURN(_("The input texture and output image must have the same number of color channels."));
  }
  
  
  with_map = (pluginParameters.input_map_id != -1 && pluginParameters.output_map_id != -1);
  /* If only one map is passed, it is ignored quietly. */
  map_in_drawable=0;
  map_out_drawable=0;

  if (with_map) 
  {
    map_in_drawable = gimp_drawable_get(pluginParameters.input_map_id);
    map_out_drawable = gimp_drawable_get(pluginParameters.output_map_id);
    /* All these can be wrong at the same time.  
    Forego userfriendliness for ease of programming: abort on first error
    */
    if ( ! equal_basetypes(map_in_drawable, map_out_drawable) )
    {
      /* Maps need the same base type. Formerly needed the same bpp. */
      ERROR_RETURN(_("The input and output maps must have the same mode"));
    } 
    if (map_in_drawable->width != corpus_drawable->width || 
               map_in_drawable->height != corpus_drawable->height) 
    {
      ERROR_RETURN(_("The input map should be the same size as the input texture image"));
    } 
    if (map_out_drawable->width != drawable->width || 
               map_out_drawable->height != drawable->height) 
    {
      ERROR_RETURN(_("The output map should be the same size as the output image"));
    }
  }

  /* 
  The engine should not be run interactively so no need to store last values. 
  I.E. the meaning of "last" is "last values set by user interaction".
  */
  
  #ifdef ANIMATE
  // Copy local pointer vars to globals
  targetDrawableCopy = drawable;
  targetMapCopy = &targetMap;
  #endif
  
  /* Error checks done, initialization work begins.  So start progress callbacks. */
  progressStart("Initializing...");
  
  /* 
  Set flags for presence of alpha channels. 
  The flag is an optimization.  Alternatives:
  - a function
  - OR standardize the internal pixmap to ALWAYS have an alpha pixelel
  initialized to VISIBLE and set from any alpha pixelel.
  */
  gboolean is_alpha_image = gimp_drawable_has_alpha(drawable->drawable_id);
  gboolean is_alpha_corpus = gimp_drawable_has_alpha(corpus_drawable->drawable_id);
  
  // Image adaption requires format indices
  // WAS  prepareImageFormatIndices(drawable, corpus_drawable, with_map, map_in_drawable);
  TFormatIndices formatIndices;
  
  guint map_count = (with_map? count_color_channels(map_in_drawable) : 0 );
    
  prepareImageFormatIndices(
    &formatIndices,
    count_color_channels(drawable),
    map_count,
    is_alpha_image,
    is_alpha_corpus,
    with_map
    );
  
  #ifdef ADAPT_SIMPLE
    /* Adapt Gimp to an engine with a simpler interface. */
    setDefaultParams(&parameters);
    ImageBuffer imageBuffer;
    ImageBuffer maskBuffer;
    
    // TODO change to new signature
    adaptGimpToSimple(drawable, &imageBuffer, &maskBuffer);  // From Gimp to simple
    g_printf("Here3\n");
    adaptSimpleAPI(&imageBuffer, &maskBuffer);        // From simple to existing engine API
    
  #else
    g_printf("Gimp adaption\n");
    /* target/context adaption */
    fetch_image_mask_map(drawable, &targetMap, formatIndices.total_bpp, 
      &targetMaskMap, 
      MASK_TOTALLY_SELECTED, 
      map_out_drawable, formatIndices.map_start_bip);
    
      #ifdef ANIMATE
      clear_target_pixels(formatIndices.colorEndBip);  // For debugging, blacken so new colors sparkle
      #endif
  
    /*  corpus adaption */
    fetch_image_mask_map(corpus_drawable, &corpusMap, formatIndices.total_bpp, 
      &corpusMaskMap,
      MASK_TOTALLY_SELECTED, 
      map_in_drawable, formatIndices.map_start_bip);
      
    // TODO These are artifacts of earlier design, not used.
    free_map(&corpusMaskMap);
    free_map(&targetMaskMap);
    
    adaptParameters(&pluginParameters, &engineParameters);
    
  #endif
  
  // After possible adaption, check size again
  g_assert(targetMap.width * targetMap.height); // Image is not empty
  g_assert(corpusMap.width * corpusMap.height); // Corpus is not empty
  
  // Done with adaption: now main image data in canonical pixmaps, etc.
  // Begin real work
  progressStart("synthesizing...");
  
  int result = engine(
    engineParameters, 
    &formatIndices, 
    &targetMap, 
    &corpusMap,
    progressUpdate,
    (void *) 0,
    &cancelFlag
    );
  
  if (result == IMAGE_SYNTH_ERROR_EMPTY_CORPUS)
  {
    ERROR_RETURN(_("The texture source is empty. Does any selection include non-transparent pixels?"));
  }
  else if  (result == IMAGE_SYNTH_ERROR_EMPTY_TARGET )
  {
    ERROR_RETURN(_("The output layer is empty. Does any selection have visible pixels in the active layer?"));
  }
  
  // Normal post-process adaption follows

  /* dump_target_points(); */ /* detailed debugging. */
  // print_post_stats();
  
  // Update Gimp image from local pixmap
  // Note this works even for test harness where ADAPT_SIMPLE
  // but then it does NOT test returning results in buffer.
  
  /* 
  We could test antiAdaptImage() here.
  But antiAdaptImage() has already been tested once on the incoming side.
  So no compelling need to test it again here.
  */
  post_results_to_gimp(drawable, targetMap); 
  
  /* Clean up */
  // Adapted
  free_map(&targetMap);
  free_map(&corpusMap);
  // GIMP
  detach_drawables(drawable, corpus_drawable, map_in_drawable, map_out_drawable);
  gimp_progress_end();
  values[0].data.d_status = GIMP_PDB_SUCCESS;
} 
static int load_mmap()
{
	char full_path[DIR_PATH_LEN] = {0};
	int i = 0;

	cdn_speed_ip_mmap = (my_mmap_t*)malloc( max_project_number * sizeof(my_mmap_t) );
	cdn_speed_area_mmap = (my_mmap_t*)malloc( max_project_number * sizeof(my_mmap_t) );
	url_page_mmap = (my_mmap_t*)malloc(max_page_per_proj * max_project_number * sizeof(my_mmap_t));

	snprintf(full_path, sizeof(full_path), "%s/%s", idc_mmap_file_dirpath,"idc_test_ip_mmap");

	idc_test_ip_mmap.type = MMAP_TYPE_IDC_IP;
	if (create_mmap(full_path, idc_mmap_size_ip, &idc_test_ip_mmap) != 0)
		return -1;
	if(idc_test_ip_mmap.mmap_head->records_num != 0)//mmap中有数据,则根据mmap更新hash表
		set_hash_for_ip_mmap(idc_hash_ip, &idc_test_ip_mmap, idc_test_ip_mmap.type);

	idc_test_area_mmap.type = MMAP_TYPE_IDC_AREA;
	snprintf(full_path, sizeof(full_path), "%s/%s", idc_mmap_file_dirpath,"idc_test_area_mmap");
	if (create_mmap(full_path, idc_mmap_size_area, &idc_test_area_mmap) != 0)
		return -1;
	//重启时重设records
	idc_test_area_mmap.records_num = idc_test_area_mmap.mmap_head->records_num = 0;

	for(i = 1; i <= max_project_number; i++) {
		snprintf(full_path, sizeof(full_path), "%s/%s%03d", cdn_mmap_file_dirpath,"cdn_speed_ip_mmap",i);

		cdn_speed_ip_mmap[ i-1 ].type = MMAP_TYPE_CDN_IP;
		if (create_mmap(full_path, cdn_mmap_size_ip, &cdn_speed_ip_mmap[ i-1 ]) != 0)
			return -1;
		if(cdn_speed_ip_mmap[ i-1 ].mmap_head->records_num != 0)
			set_hash_for_ip_mmap(cdn_hash_ip[i-1], &cdn_speed_ip_mmap[ i-1 ], cdn_speed_ip_mmap[ i-1 ].type);

		cdn_speed_area_mmap[ i-1 ].type = MMAP_TYPE_CDN_AREA;
		snprintf(full_path, sizeof(full_path), "%s/%s%03d", cdn_mmap_file_dirpath,"cdn_speed_area_mmap",i);
		if (create_mmap(full_path, cdn_mmap_size_area, &cdn_speed_area_mmap[ i-1 ]) != 0)
			return -1;
		cdn_speed_area_mmap[ i-1 ].records_num = cdn_speed_area_mmap[ i-1 ].mmap_head->records_num = 0;
	}

	//url_page's mmap
	int j, pos;

	url_page_status = (url_page_used_t*)malloc(sizeof(url_page_used_t) * max_project_number);
	if(url_page_status == NULL)
		ERROR_RETURN(("URL PAGE STATUS CREATE FAILED!") ,-1);
	for(i = 0; i < max_project_number; i++) {
		url_page_status[i].used_count = 0;
		for (j = 0; j < max_page_per_proj; j++)
			url_page_status[i].status[j] = 0;
	}
	for(i = 1; i <= max_project_number; i++) {
		for(j = 1; j <= max_page_per_proj; j++) {
			snprintf(full_path, sizeof(full_path), "%s/%s%03d_%03d",
					url_mmap_file_dirpath,"url_page_mmap", i, j);
			pos = (i-1) * max_page_per_proj + (j-1);
			url_page_mmap[pos].type = MMAP_TYPE_URL;
			if (create_mmap(full_path, url_mmap_size_page, &url_page_mmap[pos]) == -1)
				return -1;
			//加入hash表 url_page_index[i]
			if(url_page_mmap[pos].key > 0
				&& url_page_mmap[pos].value > 0
				&& url_page_mmap[pos].value < max_page_per_proj) {
				g_hash_table_insert(url_page_index[i-1], &(url_page_mmap[pos].key),
						&(url_page_mmap[pos].value));
				url_page_status[i-1].used_count ++;
				url_page_status[i-1].status[url_page_mmap[pos].value] = 1;
			}
			url_page_mmap[pos].records_num = url_page_mmap[pos].mmap_head->records_num = 0;
		}
	}
	return 0;
}
Beispiel #25
0
int fcavan_dd(int fd_in, int fd_out, off_t offset_in, off_t offset_out, off_t length, off_t size)
{
	int ret;
	struct stat st;

	println("size = %s", size2text(size));

	ret = fstat(fd_in, &st);
	if (ret < 0)
	{
		print_error("fstat input file");
		return ret;
	}

	if (length == 0)
	{
		length = st.st_size;
		if (length <= offset_in)
		{
			warning_msg("no data to be burn");
			return 0;
		}
		length -= offset_in;
	}

	if (size && length > size)
	{
		error_msg("No space left");
		ERROR_RETURN(ENOMEDIUM);
	}

	if (offset_in > 0)
	{
		ret = lseek(fd_in, offset_in, SEEK_SET);
		if (ret < 0)
		{
			print_error("seek input file");
			return ret;
		}
	}

	if (offset_out > 0)
	{
		ret = lseek(fd_out, offset_out, SEEK_SET);
		if (ret < 0)
		{
			print_error("seek output file");
			return ret;
		}
	}

	println("skip = %s", size2text(offset_in));
	println("seek = %s", size2text(offset_out));
	println("length = %s", size2text(length));

	ret = ffile_ncopy(fd_in, fd_out, length);
	if (ret < 0)
	{
		error_msg("file_ncopy");
	}

	return ret;
}
int load_linkip(char *filepath)
{
	FILE *fp;			//打开配置文件指针
	int a[4];			//临时存储点分IP的4个段
	int flag;			//标识IP是否合法
	char s[1024];	//存储从配置文件中读取的一行数据
	uint32_t i;		//for循环计数
	char c,c1;		//连续从文件的一行中读取的两个字符,用以标识变量、IP、注释行无用行
	char *eq = NULL;//字符串中表示"="的指针
	int len = 0;		//读取的字符串长度,如果是一个变量,其标识符的长度要大于0
	int idc;			//临时存储idc 编号
	int link;			//临时存储link编号
	int master;		//临时存储master编号
	link_ip_t *tmpip = NULL;//指向待探测ip

	fp = fopen(filepath,"rt");
	if (fp == NULL)
		ERROR_RETURN(("can not open config file:link_ip.congfig"), -1);

	while (!feof(fp)) {
		c = fgetc(fp);
		if ((int)c == -1) {	//EOF==-1
			break;
		}
		if (c != '$') {
			while (c != '\n' && !feof(fp)) {
				c = fgetc(fp);
			}
			continue;
		}
		if ((c1 = fgetc(fp)) != ':') {
			while (c != '\n' && !feof(fp)) {
				c = fgetc(fp);
			}
			continue;
		}

		if ('$' == c && ':' ==c1) {
			//memset(s,0,1024);
			len = 0;
			fgets(s,1024,fp);
			if ((eq = strchr(s,'=')) == NULL)
				continue;
			len = eq - s;
			if ( len <= 0 )
				continue;

			if (bcmp(s,"link_ip",len) == 0) {
				flag = 0;
				idc = link = master = a[0] = a[1] = a[2] = a[3] = -1;
				sscanf(eq + 1,"%d,%d,%d.%d.%d.%d,%d",&idc,&link,&a[0],&a[1],&a[2],&a[3],&master);
				if(idc <= 0 || link <= 0)
					continue;
				for (i = 0;i <= 3;i++) {
					if ( a[i] > 255 || a[i] < 0 ) {
						ERROR_LOG("[warning]:illegal link ip in file\"%s\"[%s],ignored",filepath,s);
						flag = 1;	//IP有问题!则跳出并置位错误标记为真
						break;
					}
				}//for
				if (!flag) {
					if ((tmpip = (link_ip_t*)malloc(sizeof(link_ip_t))) == NULL)
						ERROR_RETURN(("Load_Link_Config:read ip.malloc failed!"), -1);

					tmpip->ip = a[0]*256*256*256 + a[1]*256*256 + a[2]*256 + a[3];
					tmpip->idc_observer = idc;
					tmpip->idc_master = master;
					tmpip->link_no = link;
					snprintf((char*)tmpip->hashkey, sizeof(tmpip->hashkey),
								"%d%d", tmpip->idc_observer, tmpip->ip);
					tmpip->next = NULL;
					if (link_ip_set == NULL)
						link_ip_set = tmpip;
					else {
						tmpip->next = link_ip_set;
						link_ip_set = tmpip;
					}
					if (g_hash_table_lookup(link_hash_ip, tmpip->hashkey ) == NULL)
						g_hash_table_insert(link_hash_ip, tmpip->hashkey, tmpip);
				}//if legal ip
			}//if linkip
		}//if $:
	}//while
	fclose(fp);
	return 0;
}
Beispiel #27
0
Glove* Glove::create(SerialPort port) {
    CCyberGlove *glove = new CCyberGlove(getSystemName(port), B115200);
    if (glove == NULL) ERROR_RETURN("problem at initialization", NULL)
    return new Glove(glove);
    }
Beispiel #28
0
int main() {
    init();
    std::cout << sizeof(D) << std::endl; 
    
    #ifdef WITH_PAPI
    int EventSet = PAPI_NULL;
    int retval;
	char errstring[PAPI_MAX_STR_LEN];
	long long values[NUM_EVENTS];

    if((retval = PAPI_library_init(PAPI_VER_CURRENT)) != PAPI_VER_CURRENT )
	{
        fprintf(stderr, "Error: %s\n", errstring);
        exit(1);
	}

    /* Creating event set   */
    if ((retval=PAPI_create_eventset(&EventSet)) != PAPI_OK)
        ERROR_RETURN(retval);
  
    /* Add the array of events PAPI_TOT_INS and PAPI_TOT_CYC to the eventset*/
    if ((retval=PAPI_add_event(EventSet, PAPI_L1_DCM)) != PAPI_OK)
        ERROR_RETURN(retval);

    if ( PAPI_add_event( EventSet, PAPI_L2_DCM ) != PAPI_OK)
        printf("Error PAPI_add_event \n" );
  
    /* Start counting */
    if ( (retval=PAPI_start(EventSet)) != PAPI_OK)
        ERROR_RETURN(retval);
    #endif

    for(int i = 0; i <= n; i++) {
        for(int j = 0; j <= n; j++) {
            // Calculate D
            if(i > 0 && j > 0) {
                D[i][j] = D[i-1][j];
                
                if(G[i-1][j] + GI < D[i][j]) {
                    D[i][j] = G[i-1][j] + GI;
                }
                D[i][j] += GE;
            }
            
            if(i == 0 && j > 0) {
                D[i][j] = G[0][j] + GE;
            }

            // Calculate I
            if(i > 0 && j > 0) {
                I[i][j] = I[i][j-1];
                
                if(G[i][j-1] + GI < I[i][j]) {
                    I[i][j] = G[i][j-1] + GI;
                }

                I[i][j] += GE;
            }   

            if(i > 0 && j == 0) {
                I[i][j] = G[i][0] + GE;
            }

            // Calculate G
            if(i > 0 && j > 0) {
                G[i][j] = G[i-1][j-1]+S(X[i-1],Y[j-1]);
                
                if(D[i][j] < G[i][j]) {
                    G[i][j] = D[i][j];
                }

                if(I[i][j] < G[i][j]) {
                    G[i][j] = I[i][j];
                }
            }
        }      
    }

    #ifdef WITH_PAPI
    if ( (retval=PAPI_stop(EventSet,values)) != PAPI_OK)
        ERROR_RETURN(retval);
    
    std::cout << "L1 Misses: " << values[0] << " L2 Misses: " << values[1] << std::endl;
    /*
    double tot_access = 4 * n * n *n;
    double miss_ratio = values[0] / tot_access;
    printf("%d\t%f\n",n,miss_ratio);
    */

    if ( (retval=PAPI_remove_event(EventSet,PAPI_L1_DCM))!=PAPI_OK)
        ERROR_RETURN(retval);
  
    if ( (retval=PAPI_remove_event(EventSet,PAPI_L2_DCM))!=PAPI_OK)
        ERROR_RETURN(retval);

    /* Free all memory and data structures, EventSet must be empty. */
    if ( (retval=PAPI_destroy_eventset(&EventSet)) != PAPI_OK)
        ERROR_RETURN(retval);
  
    /* free the resources used by PAPI */
    PAPI_shutdown();
    #endif

    std::cout << G[n][n] << std::endl;
    reconstruct_path(); 
    clean_up();
}