From 69b2a647c88a97edd7a9854cbb5b7daaa01569d4 Mon Sep 17 00:00:00 2001 From: SisMaker <1713699517@qq.com> Date: Sun, 11 Oct 2020 01:27:09 +0800 Subject: [PATCH] =?UTF-8?q?=E9=83=A8=E5=88=86=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/httpSocket/utSocket.erl | 19 +- src/srvNodeMgr/baizhan/misc/config.erl | 124 ---- src/srvNodeMgr/baizhan/misc/lib_send.erl | 202 ------ src/srvNodeMgr/baizhan/misc/lib_sys.erl | 24 - src/srvNodeMgr/baizhan/misc/misc.erl | 367 +--------- src/srvNodeMgr/baizhan/misc/util.erl | 633 +----------------- .../tools/gameWorld/test/misc/config.erl | 332 --------- .../gameWorld/test/misc/dynamic_compile.erl | 270 -------- .../test/misc/game_alarm_handler.erl | 41 -- .../tools/gameWorld/test/misc/game_timer.erl | 131 ---- .../tools/gameWorld/test/misc/logger_h.erl | 238 ------- .../tools/gameWorld/test/misc/loglevel.erl | 114 ---- .../tools/gameWorld/test/misc/misc.erl | 189 ------ src/uuidMd5/utMd5.erl | 2 +- 14 files changed, 37 insertions(+), 2649 deletions(-) delete mode 100644 src/srvNodeMgr/baizhan/misc/config.erl delete mode 100644 src/srvNodeMgr/baizhan/misc/lib_send.erl delete mode 100644 src/srvNodeMgr/baizhan/misc/lib_sys.erl delete mode 100644 src/srvNodeMgr/tools/gameWorld/test/misc/config.erl delete mode 100644 src/srvNodeMgr/tools/gameWorld/test/misc/dynamic_compile.erl delete mode 100644 src/srvNodeMgr/tools/gameWorld/test/misc/game_alarm_handler.erl delete mode 100644 src/srvNodeMgr/tools/gameWorld/test/misc/game_timer.erl delete mode 100644 src/srvNodeMgr/tools/gameWorld/test/misc/logger_h.erl delete mode 100644 src/srvNodeMgr/tools/gameWorld/test/misc/loglevel.erl diff --git a/src/httpSocket/utSocket.erl b/src/httpSocket/utSocket.erl index 65a800a..c0d2373 100644 --- a/src/httpSocket/utSocket.erl +++ b/src/httpSocket/utSocket.erl @@ -1,14 +1,14 @@ -module(utSocket). -export([ - socket2ip/1 + socketToIpStr/1 , socket2port/1 , str2ip/1 ]). %% socket转IP -socket2ip(Socket) -> +socketToIpStr(Socket) -> case inet:peername(Socket) of {ok, {{A, B, C, D}, _}} -> string:join(lists:map(fun com_type:to_list/1, [A, B, C, D]), "."); @@ -16,6 +16,21 @@ socket2ip(Socket) -> "" end. +%% 获取ip +socketToIpTuple(Socket) -> + case catch inet:peername(Socket) of + {ok, {Ip, _Port}} -> + Ip; + _ -> + case catch ssl:peername(Socket) of + {ok, {Ip, _Port}} -> + Ip; + _ -> + {0, 0, 0, 0} + end + end. + + socket2port(Socket) -> case inet:peername(Socket) of {ok, {_, Port}} -> Port; diff --git a/src/srvNodeMgr/baizhan/misc/config.erl b/src/srvNodeMgr/baizhan/misc/config.erl deleted file mode 100644 index ef52014..0000000 --- a/src/srvNodeMgr/baizhan/misc/config.erl +++ /dev/null @@ -1,124 +0,0 @@ -%%%----------------------------------- -%%% @Author : gaomeng 595088880@qq.com -%%% @Created : 2017/10/17 -%%% @Doc : APP启动相关 -%%%----------------------------------- --module(config). --include("common.hrl"). --define(APP, server). - --export([ - config/1 - , server_ids/0 - , listen_port/0 - , get_ticket/0 - , get_enter_ticket/0 - , get_platform/0 - , get_create_max_num/0 - , is_gm_open/0 - , set_gm_open/1 - , get_white_ip/0 - , add_white_ip/1 - , del_white_ip/1 - , open_date/0 - , merge_date/0 - , set_open_date/1 - , set_merge_date/1 - , print_cmd/0 - , set_print_cmd/1 - , version/0 - , is_https/0 -]). - -%% @doc 是否是HTTPS; return true|false -is_https() -> - case catch config(is_https) of - {'EXIT', _} -> - false; - Val -> - Val - end. - -%% @doc 获取版本 -version() -> - case catch config(version) of - {'EXIT', _} -> - "未知版本"; - Val -> - Val - end. - -%% @doc 获取协议打印状态 -print_cmd() -> - config(print_cmd). - -%% @doc 设置协议打印状态 -set_print_cmd(Flag) -> - application:set_env(?APP, print_cmd, Flag). - -%% @doc 设置开服时间 -set_open_date(Date) -> - application:set_env(?APP, open_date, Date, [{persistent, true}]). - -%% @doc 设置合服时间 -set_merge_date(Date) -> - application:set_env(?APP, merge_date, Date, [{persistent, true}]). - -%% @spec open_date() -> {Year, Month, Day} -%%@ doc 获取开服日期 -open_date() -> - config(open_date). - -%% @spec merge_date() -> {Year, Month, Day} -%%@ doc 获取合服日期 -merge_date() -> - config(merge_date). - -%% @doc 添加白名单 -add_white_ip(Ip) -> - List = get_white_ip(), - List1 = [Ip | List], - application:set_env(?APP, white_ip, List1). - -%% @doc 删除白名单 -del_white_ip(Ip) -> - List = get_white_ip(), - List1 = lists:delete(Ip, List), - application:set_env(?APP, white_ip, List1). - -%% @doc 获取白名单 -get_white_ip() -> - config(white_ip). - -set_gm_open(Flag) -> - application:set_env(?APP, gm, Flag). - -is_gm_open() -> - config(gm). - -get_enter_ticket() -> - config(enter_ticket). - -get_ticket() -> - config(ticket). - -listen_port() -> - config(listen_port). - -server_ids() -> - config(server_ids). - -get_platform() -> - config(platform). - -get_create_max_num() -> - config(create_max_num). - -%% @doc 根据KEY获取对应的值 -config(Key) -> - case application:get_env(?APP, Key) of - {ok, Val} -> - Val; - _ -> - throw(undefined) - end. \ No newline at end of file diff --git a/src/srvNodeMgr/baizhan/misc/lib_send.erl b/src/srvNodeMgr/baizhan/misc/lib_send.erl deleted file mode 100644 index 2018190..0000000 --- a/src/srvNodeMgr/baizhan/misc/lib_send.erl +++ /dev/null @@ -1,202 +0,0 @@ -%%%----------------------------------- -%%% @Author : gaomeng 595088880@qq.com -%%% @Created : 2017/1/30 -%%% @Doc : 发送相关 -%%%----------------------------------- --module(lib_send). --include("common.hrl"). --include("scene.hrl"). --include("move.hrl"). --include("guild.hrl"). --include_lib("stdlib/include/ms_transform.hrl"). - --export([ - send/2, - pack_send/3, - pack_send/4, - pack_send_msg/2, - - send_to_scene/1, - send_to_scene/2, - - async_send_scene/2, - async_send_scene/3, - - send_to_world/1, - send_to_world/2, - send_to_world/3, - - send_to_guild/3, - - async_online/3, - async_online/4 -]). - -%% @doc 全服异步在线玩家执行函数 -async_online(M, F, Args) -> - async_online(0, M, F, Args). - -async_online(RoleId, M, F, Args) -> - spawn(fun() -> - case ets:info(?ETS_ONLINE) of - undefined -> - ok; - _ -> - L = ets:tab2list(?ETS_ONLINE), - [svr_role:apply(async, Pid, {M, F, Args}) || #role{pid = Pid, id = TemRoleId} <- L, RoleId =/= TemRoleId] - end - end). - -%% @doc 公会广播 -send_to_guild(GuildId, Cmd, List) when is_integer(GuildId) -> - svr_guild:apply(async, GuildId, {lib_send, send_to_guild, [Cmd, List]}); -send_to_guild(#guild{members = Members}, Cmd, List) -> - case catch prot:encode(Cmd, List) of - {ok, Bin} -> - F = fun(#guild_member{role_id = RoleId}) -> - case lib_account:get_role_pid(RoleId) of - Pid when is_pid(Pid) -> - send(Pid, Bin); - _ -> - ok - end - end, - [F(M) || M <- Members]; - Ret -> - ?ERR("Cmd:~w use pack_send, reason:~w", [Cmd, Ret]), - ok - end, - ok. - -%%世界广播 -send_to_world(RoleId, Bin) -> - spawn(fun() -> - [send(Sid, Bin) || #role{id = Id, sid = Sid} <- ets:tab2list(?ETS_ONLINE), Id =/= RoleId] - end). - -send_to_world(Bin) -> - spawn(fun() -> - [send(Sid, Bin) || #role{sid = Sid} <- ets:tab2list(?ETS_ONLINE)] - end). - -%% @doc 世界广播(有等级限制) -send_to_world(level, ReqLevel, Bin) -> - spawn(fun() -> - [send(Sid, Bin) || #role{level = Level, sid = Sid} <- ets:tab2list(?ETS_ONLINE), Level >= ReqLevel] - end); - -send_to_world(RoleId, Cmd, List) -> - case catch prot:encode(Cmd, List) of - {ok, Bin} -> - spawn(fun() -> - [send(Sid, Bin) || #role{id = Id, sid = Sid} <- ets:tab2list(?ETS_ONLINE), Id =/= RoleId] - end); - Ret -> - ?ERR("Cmd:~w use pack_send, reason:~w", [Cmd, Ret]), - ok - end. - -%%场景广播 -send_to_scene(Rid, BinData) -> - AllRole = svr_scene_role:get_all(), - F = fun(Role) -> - case Role#scene_role.id =/= Rid of - true -> - send(Role#scene_role.sid, BinData); - _ -> - ok - end - end, - [F(P) || P <- AllRole]. - -send_to_scene(BinData) -> - AllRole = svr_scene_role:get_all(), - F = fun(Role) -> - send(Role#scene_role.sid, BinData) - end, - [F(P) || P <- AllRole]. - -%% @doc 其他进程发送场景广播 -async_send_scene(ScenePid, BinData) -> - async_send_scene(ScenePid, BinData, 0). - -async_send_scene(ScenePid, BinData, RoleId) when is_pid(ScenePid) -> - svr_scene:apply(async, ScenePid, {svr_scene_info, async_send_scene, [RoleId, BinData]}); -async_send_scene(_, _, _) -> - ok. - -%% @doc 打包 -pack_send(Node, Rid = #node_rid{id = RoleId}, Cmd, List) -> - case Node =:= node() of - true -> - pack_send(RoleId, Cmd, List); - _ -> - svr_kfnode:send_role(Node, [Rid], lib_send, pack_send, [Cmd, List]) - end. - -pack_send(RoleId, Cmd, List) when is_integer(RoleId) -> - case lib_account:get_role_pid(RoleId) of - Pid when is_pid(Pid) -> - pack_send(Pid, Cmd, List); - _ -> - ok - end; -pack_send(#node_rid{id = RoleId}, Cmd, List) -> - pack_send(RoleId, Cmd, List); -pack_send(#role{sid = Sid}, Cmd, List) -> - pack_send(Sid, Cmd, List); -pack_send(Sid, Cmd, List) -> - case misc:is_process_alive(Sid) of - true -> - case catch prot:encode(Cmd, List) of - {ok, Bin} -> - send(Sid, Bin); - Ret -> - ?ERR("Cmd:~w use pack_send, reason:~w", [Cmd, Ret]), - ok - end; - _R -> - ok - end, - ok. - -send(#role{sid = Sid}, Bin) -> - send(Sid, Bin); -send(Sid, Bin) -> - case catch config:config(print_send_cmd) of - true -> - <<_L:32, Cmd:32, _Data/binary>> = Bin, - svr_handle_mgr:listen_cmd(Cmd, byte_size(Bin)); - _ -> - ok - end, - Sid ! {'send', Bin}, - ok. - -pack_send_msg(#node_rid{id = RoleId}, List) -> - pack_send_msg(RoleId, List); -pack_send_msg(RoleId, List) when is_integer(RoleId) -> - case ets:lookup(?ETS_ONLINE, RoleId) of - [#role{sid = Sid} | _] -> - case misc:is_process_alive(Sid) of - true -> - pack_send_msg(Sid, List); - _ -> - ok - end; - _ -> - ok - end; -pack_send_msg(#role{sid = Sid}, List) -> - pack_send_msg(Sid, List); -pack_send_msg(Sid, [Type, {Code, Vals}]) -> - pack_send_msg(Sid, [Type, 0, Code, Vals]); -pack_send_msg(Sid, [Type, Code]) -> - pack_send_msg(Sid, [Type, 0, Code, ""]); -pack_send_msg(Sid, [Type, SubType, {Code, Vals}]) -> - pack_send_msg(Sid, [Type, SubType, Code, Vals]); -pack_send_msg(Sid, [Type, SubType, Code]) -> - pack_send_msg(Sid, [Type, SubType, Code, ""]); -pack_send_msg(Sid, List) -> - pack_send(Sid, 10100, List), - ok. diff --git a/src/srvNodeMgr/baizhan/misc/lib_sys.erl b/src/srvNodeMgr/baizhan/misc/lib_sys.erl deleted file mode 100644 index e1113b7..0000000 --- a/src/srvNodeMgr/baizhan/misc/lib_sys.erl +++ /dev/null @@ -1,24 +0,0 @@ -%%%----------------------------------- -%%% @Author : gaomeng 595088880@qq.com -%%% @Created : 2017/10/17 -%%% @Doc : 系统数据库保存相关信息 -%%%----------------------------------- --module(lib_sys). --include("common.hrl"). --export([ - get_var/1 -]). - -%% @doc 获取对应数据库字段配置 -get_var(TarName) when is_list(TarName) -> - Sql = io_lib:format(<<"SELECT `value` FROM `sys_var` WHERE `name` = '~s' limit 1;">>, [TarName]), - case db:get_one(Sql) of - [] -> - util:term_to_bitstring([]); - <<>> -> - util:term_to_bitstring([]); - Ret -> - Ret - end; -get_var(Obj) -> - get_var(util:to_list(Obj)). \ No newline at end of file diff --git a/src/srvNodeMgr/baizhan/misc/misc.erl b/src/srvNodeMgr/baizhan/misc/misc.erl index 9d6c94d..02e9c98 100644 --- a/src/srvNodeMgr/baizhan/misc/misc.erl +++ b/src/srvNodeMgr/baizhan/misc/misc.erl @@ -1,18 +1,4 @@ -%%%----------------------------------- -%%% @Module : misc -%%% @Author : lizemao -%%% @Created : 2014.2.24 -%%% @Description: misc -%%%----------------------------------- -module(misc). - -%% -%% Include files -%% --include("common.hrl"). --include("cache.hrl"). --include("item.hrl"). --include_lib("kernel/include/file.hrl"). %% %% Exported Functions %% @@ -21,8 +7,6 @@ register/3, unregister/2, is_process_alive/1, - create_process_name/2, - to_atom/1, % t/1, % t/2, % tr/1, @@ -30,31 +14,19 @@ % tan/1, % t_clear/0, dump_process_info/1 - , u/1 - , hot/0 - , hot_beam/1 %% 直接加载更新变动beam文件,运营服使用 , ets_mem/0 , tcp_links/0 , top_back/0 , top/0 , request/1 - , u_one/1 - , stop/0 - , del_ref/1 ]). -export([ - role_cmd/3 - , gm/2 - , check_mem/0 - , check_mem/1 - , online_num/0 - , is_cross/0 + check_mem/1 ]). -export([ - decompile/1 - , pstack/1 + pstack/1 , etop/0 , etop_mem/0 , etop_stop/0 @@ -74,24 +46,10 @@ , trace/2 , trace_stop/0 - , proc_mem_all/1 - , proc_mem/1 - , crash_dump/0 , process_infos/0 ]). --export([check_item/0, ints2str/2]). - -%% -%% API Functions -%% - -%% @doc 删除ref -del_ref(Ref) when is_reference(Ref) -> - erlang:cancel_timer(Ref); -del_ref(_) -> - ok. %% @doc 节点所有进程信息 process_infos() -> @@ -147,30 +105,6 @@ rfc1123_local_date({{YYYY, MM, DD}, {Hour, Min, Sec}}) -> rfc1123_local_date(Epoch) when erlang:is_integer(Epoch) -> rfc1123_local_date(calendar:gregorian_seconds_to_datetime(Epoch + 62167219200)). -%% @doc etop 无法应对10w+ 进程节点, 下面代码就没问题了;找到可疑proc后通过pstack、message_queu_len 排查原因 -proc_mem_all(SizeLimitKb) -> - Procs = [{undefined, Pid} || Pid <- erlang:processes()], - proc_mem(Procs, SizeLimitKb). - -proc_mem(SizeLimitKb) -> - Procs = [{Name, Pid} || {_, Name, Pid, _} <- release_handler_1:get_supervised_procs(), erlang:is_process_alive(Pid)], - proc_mem(Procs, SizeLimitKb). - -proc_mem(Procs, SizeLimitKb) -> - SizeLimit = SizeLimitKb * 1024, - {R, Total} = lists:foldl(fun({Name, Pid}, {Acc, TotalSize}) -> - case erlang:process_info(Pid, total_heap_size) of - {_, Size0} -> - Size = Size0 * 8, - case Size > SizeLimit of - true -> {[{Name, Pid, Size} | Acc], TotalSize + Size}; - false -> {Acc, TotalSize} - end; - _ -> {Acc, TotalSize} - end - end, {[], 0}, Procs), - R1 = lists:keysort(3, R), - {Total, lists:reverse(R1)}. %trace Mod 所有方法的调用 trace(Mod) -> @@ -270,25 +204,8 @@ pstack(Reg) when is_atom(Reg) -> pstack(Pid) -> io:format("~s~n", [element(2, process_info(Pid, backtrace))]). -%% @doc 反编译代码 -decompile(Mod) -> - {ok, {_, [{abstract_code, {_, AC}}]}} = beam_lib:chunks(code:which(Mod), [abstract_code]), - ?INF("~s~n", [erl_prettypr:format(erl_syntax:form_list(AC))]). - -%% @doc 在线人数 -online_num() -> - ets:info(?ETS_ONLINE, size). - -%% @doc 检测占用总内存大运600M的全部强制GC -check_mem() -> - Total = erlang:memory(total), - case Total > 600000000 of - true -> - spawn(fun() -> [erlang:garbage_collect(Pid) || Pid <- processes()] end); - _ -> - ok - end. -% check_mem(1000000000). + + %% 检查溢出的内存,强制gc, 并写入日志分析 check_mem(MemLim) -> @@ -308,137 +225,6 @@ check_mem(MemLim) -> end end, erlang:processes()). -%% @doc 发送GM命令 -gm(RoleId, Content) -> - role_cmd(RoleId, 11600, [Content]). - -%% @doc 发送玩家协议 -role_cmd(RoleId, Cmd, Data) -> - svr_role:apply(async, RoleId, {lib_role, async_cmd, [Cmd, Data]}). - -%% @doc 关闭应用 -stop() -> - ?INF("server_starting_stop"), - case is_cross() of - true -> - cross_stop(); - _ -> - common_stop() - end. - -%% @doc 游戏服关闭 -common_stop() -> - AllRoles = ets:tab2list(?ETS_ONLINE), - [Pid ! {'stop', server_stop} || #role{pid = Pid} <- AllRoles],%玩家下线 - cowboy:stop_listener(http), - catch svr_cache_mgr:do_save(), - catch svr_chat:save_chat(), - catch svr_rank:hand_save(), - catch svr_log:hand_save(), - - case catch check_item() of - {'EXIT', Res} -> - ?INF("error:~p", [Res]); - _ -> - ok - end, - - - ?INF("server_stop"), - - init:stop(). - -%% @doc 检测物品消失 -check_item() -> - List = ets:tab2list(?ETS_CACHE_ITEM_ROLE), - check_item(List). - -check_item([{RoleId, Ids = [_ | _]} | T]) -> - SelectSql = io_lib:format(<<"select id from player_item where role_id=~p;">>, [RoleId]), - IdVals = db:execute(SelectSql), - case filter_item_ids(IdVals, Ids, []) of - [_ | IdStrs] -> - Sql = io_lib:format(<<"delete from player_item where id in (~s);">>, [IdStrs]), - db:execute(Sql); - _ -> - ok - end, - - save_eq(Ids), - - check_item(T); -check_item([_ | T]) -> - check_item(T); -check_item([]) -> - ok. - -%% @doc 保存玩家装备信息 -save_eq(Ids) -> - case find_eq_item(Ids, []) of - [_ | SqlVals] -> - Sql = io_lib:format(?SQL_ITEM_BATCH_REPLACE, [SqlVals]), - db:execute(Sql); - _ -> - ok - end. - -find_eq_item([Id | T], L) -> - L1 = - case svr_cache_item:find_item(Id) of - Item = #item{slot = Slot} -> - case Slot > 0 orelse lib_awake_equip:is_awake(Item) of - true -> - "," ++ lib_item_dict:make_batch_insert_sql_one(Item) ++ L; - _ -> - L - end; - _ -> - L - end, - find_eq_item(T, L1); -find_eq_item([], L) -> - L. - -%% @doc 筛选物品 -filter_item_ids([[Id] | T], Ids, L) -> - L1 = - case lists:member(Id, Ids) of - false -> - IdStr = integer_to_list(Id), - "," ++ IdStr ++ L; - _ -> - L - end, - filter_item_ids(T, Ids, L1); -filter_item_ids([], _, L) -> - L. - -ints2str([Id | T], L) -> - IdStr = integer_to_list(Id), - case T of - [] -> - ints2str(T, IdStr ++ L); - _ -> - ints2str(T, "," ++ IdStr ++ L) - end; -ints2str([], L) -> - L. - -%% @doc 中央服关闭 -cross_stop() -> - catch svr_kfboss_awake_mgr:stop(), - catch svr_kfnode:stop(), - init:stop(). - -%% @doc 是否是中央服 -is_cross() -> - case config:get_platform() of - "cross" -> - true; - _ -> - false - end. - %% @doc 寻找PID whereis_name({local, Atom}) -> erlang:whereis(Atom); @@ -476,99 +262,6 @@ is_process_alive(Pid) -> _:_ -> false end. -create_process_name(Prefix, List) -> - to_atom(lists:concat(lists:flatten([Prefix] ++ lists:map(fun(T) -> ['_', T] end, List)))). - -to_atom(Msg) when is_atom(Msg) -> - Msg; -to_atom(Msg) when is_binary(Msg) -> - list_to_atom2(binary_to_list(Msg)); -to_atom(Msg) when is_list(Msg) -> - list_to_atom2(Msg); -to_atom(_) -> - throw(other_value). %%list_to_atom(""). - -list_to_atom2(List) when is_list(List) -> - case catch (list_to_existing_atom(List)) of - {'EXIT', _} -> erlang:list_to_atom(List); - Atom when is_atom(Atom) -> Atom - end. - -%%------------------------------------------------ -%% Admin API -%%------------------------------------------------ -%% @spec hot/0 -> ok -%% @doc 编译源码并热更 TODO:会加载修改时间在六分钟之内的模块 -%% @doc 开发环境这里需要编译,线上环境直接加载更新的beam文件 -hot() -> - HotTime = svr_handle_mgr:hot_time() - 360, - Now = ?NOW, - case max(0, Now - HotTime) of - TimeLimit when TimeLimit > 0 -> - hot_beam(TimeLimit), - - % 热更后需要刷新的活动 - svr_activity_fl:reflash(), - - ok; - _ -> - ok - end. - -hot_beam(TimeLimit) when TimeLimit > 0 -> - Now = ?NOW, - FilePaths = all_ebin_file(), - io:format("-----------------------------------------------~n"), - io:format("hots ~p ~p~n", [node(), config:server_ids()]), - io:format("~n"), - lists:foreach(fun(FilePath) -> - case file:read_file_info(FilePath) of - {ok, #file_info{mtime = Mtime}} -> - Time = util:datetime_to_seconds(Mtime), - case Now - Time =< TimeLimit of - true -> - Module = filename:basename(FilePath, ".beam"), - u(list_to_atom(Module)); - _ -> - ok - end; - _ -> - ok - end - end, FilePaths), - io:format("~n"), - io:format("-----------------------------------------------~n"); -hot_beam(_) -> - ok. - -%% @doc 获取代码所有 -all_ebin_file() -> - LogicNames = filelib:wildcard("../ebin/*.beam"), - DepsNames = filelib:wildcard("../deps/*/ebin/*.beam"), - DepsNames ++ LogicNames. - -%% @doc 热更 -u(M) when not is_list(M) -> - u([M], []); -u(List) -> - u(List, []). - -u([], List) -> - List; -u([Module | T], List) -> - Ret = u_one(Module), - u(T, [{Ret, Module} | List]). - -u_one(Module) -> - case c:nl(Module) of - abcast -> - ?PRINT("~w:load ~20w ok", [calendar:local_time(), Module]), - ok; - _ -> - ?PRINT("~w:load ~20w fail", [calendar:local_time(), Module]), - error - end. - %% @spec top() -> ok %% @doc 查看系统当前的综合信息 top() -> @@ -579,11 +272,9 @@ top() -> ProcMemUsed = erlang:memory(processes_used), EtsMemAlc = erlang:memory(ets), MemTot = erlang:memory(total), - RoleNum = ets:info(?ETS_ONLINE, size), %PetNum = all_pets(), io:format( "++++++++++++++++++++++++++++++++++++++++++~n" - " ServerId: ~p~n" " Node: ~p~n" " Erlang Ver: ~p~n" " Free Threads: ~p~n" @@ -592,9 +283,8 @@ top() -> " Erlang VM Used Memory: ~pMb~n" " Process Limit: ~p~n" " Process Used: ~p~n" - " Online Players: ~p~n" "++++++++++++++++++++++++++++++++++++++++++~n" - , [config:server_ids(), node(), Release, SchedNum, ProcMemUsed / 1024 / 1024, EtsMemAlc / 1024 / 1024, MemTot / 1024 / 1024, ProcLimit, ProcCount, RoleNum]), + , [node(), Release, SchedNum, ProcMemUsed / 1024 / 1024, EtsMemAlc / 1024 / 1024, MemTot / 1024 / 1024, ProcLimit, ProcCount]), ok. %% @doc 运维要用 @@ -606,7 +296,6 @@ top_back() -> ProcMemUsed = erlang:memory(processes_used), EtsMemAlc = erlang:memory(ets), MemTot = erlang:memory(total), - RoleNum = ets:info(?ETS_ONLINE, size), Str = io_lib:format( " Erlang 版本: ~p~n" " 可使用的调度线程: ~p~n" @@ -615,8 +304,7 @@ top_back() -> " Erlang系统占用内存: ~pMb~n" " 可创建进程数量上限: ~p~n" " 当前进程数: ~p~n" - " 在线角色数: ~p~n" - , [Release, SchedNum, ProcMemUsed / 1024 / 1024, EtsMemAlc / 1024 / 1024, MemTot / 1024 / 1024, ProcLimit, ProcCount, RoleNum]), + , [Release, SchedNum, ProcMemUsed / 1024 / 1024, EtsMemAlc / 1024 / 1024, MemTot / 1024 / 1024, ProcLimit, ProcCount]), binary_to_list(list_to_binary(Str)). %% @spec ets_mem() -> term() @@ -631,12 +319,13 @@ ets_mem() -> end end, L), L1 = lists:sublist(lists:reverse(lists:keysort(2, Mems)), 30), - ?PRINT("~n--------------------------------------------------~n" + io:format("~n--------------------------------------------------~n" "~-30w ~w~n--------------------------------------------------~n" , [table, used_memory]), - lists:foreach(fun({Tab, Mem}) -> - ?PRINT("~-30w ~wKb~n", [Tab, Mem / 1024]) - end, L1). + lists:foreach( + fun({Tab, Mem}) -> + io:format("~-30w ~wKb~n", [Tab, Mem / 1024]) + end, L1). %% @spec tcp_links() -> Info %% @doc 统计tcp链接 @@ -650,36 +339,7 @@ tcp_links() -> end end, L1 = lists:filter(F, L), - ?PRINT("~n当前socket数量(包括链接数据库的socket): ~w~n", [length(L1)]). - -% %% @doc 根据账户名trace -% tan(AcountName) -> -% Bin = unicode:characters_to_binary(AcountName), -% [t(UserID)||#ets_user{account_name = Name, id = UserID} <- ets:tab2list(?ETS_ONLINE), Name =:= Bin]. - -% %% @doc 根据角色名trace -% tun(UserName) -> -% Bin = unicode:characters_to_binary(UserName), -% [t(UserID) ||#ets_user{name = Name, id = UserID} <- ets:tab2list(?ETS_ONLINE), Name =:= Bin]. - -% %% @doc 根据角色ID trace 方法 -% t(UserID, MFN) -> -% t(UserID), -% t(MFN). - -% t({M, F, Num}) -> -% dbg:tpl(M, F, Num, []); -% t(UserID) -> -% dbg:tracer(), -% Pid = misc:whereis_name({global, player_process_name(UserID)}), -% dbg:p(Pid, c). - -% tr({M, F, Num}) -> -% dbg:tpl(M, F, Num, [{'_', [], [{return_trace}]}]). - -% %% @doc 停止 trace -% t_clear() -> -% dbg:stop_clear(). + io:format("~n当前socket数量(包括链接数据库的socket): ~w~n", [length(L1)]). %% @doc 备份进程信息 @@ -713,7 +373,8 @@ dump_process_info(Pid) -> (E) -> io:format(FileHandle, "~w~n", [E]) end, Info); - _ -> ?PRINT("not find pid info") + _ -> + io:format("not find pid info") end, file:close(FileHandle). diff --git a/src/srvNodeMgr/baizhan/misc/util.erl b/src/srvNodeMgr/baizhan/misc/util.erl index 5ae5028..efe0f8f 100644 --- a/src/srvNodeMgr/baizhan/misc/util.erl +++ b/src/srvNodeMgr/baizhan/misc/util.erl @@ -1,100 +1,30 @@ -%%%----------------------------------- -%%% @Author : gaomeng 595088880@qq.com -%%% @Created : 2017/1/23 -%%% @Doc : 辅助函数库 -%%%----------------------------------- - -module(util). --include("common.hrl"). -export([ - unixtime/0, - longunixtime/0, - local_time/0, - - cn/1, - datetime_to_seconds/1, - ifelse/3, string_width/1, - safe_create_ets/2, rand_list/1, - term_to_string/1, - term_to_bitstring/1, - bitstring_to_term/1, - bitstring_to_obj/1, - string_to_term/1, - get_max_svrid/0, - to_list/1, - check_name_length/1, rm_str_space/1, rm_str_lr_space/1, - same_str/2, - unixtime_to_now/1, - unixtime_to_localtime/1, - get_day_of_week/0, - get_day_of_week/1, - get_secs_from_midnight/0, - get_secs_from_midnight/1, - time_to_seconds/1, - other_day/2, - make_cdkey/2, - parse_idstr/1, - robot_name/0, - localtime2date/0, - localtime2date/1, - check_sen_keyword/2, - check_round_level/4, - next_sec/1 + check_sen_keyword/2 ]). -export([ - quick_sort/2 - , upset_list/1 + upset_list/1 , insert_last/2 ]). --export([ - open_day/0 - , merge_day/0 - , is_merge/0 - , week_diff_day/2 - , del_timer_ref/1 - , time_diff_sec/2 - , escape/1 - , under_week_time/2 - , calc_week_sec/1 - , calc_week_sec/2 - - , boolen2num/1 - , check_roleid/1 - , sort_red/0 - , decompile/1 -]). -compile(export_all). -%% @doc 测试 -test() -> - L1 = [], - L2 = [], - Keys = [{2, ?true}], - L11 = quick_sort(L1, Keys), - ?INF("cmd1:~p~n", [L11]), - L22 = quick_sort(L2, Keys), - ?INF("cmd2:~p~n", [L22]), - ok. - -%% @doc 反编代码 -decompile(Mod) -> - {ok, {_, [{abstract_code, {_, AC}}]}} = beam_lib:chunks(code:which(Mod), [abstract_code]), - ?PRINT("~s~n", [erl_prettypr:format(erl_syntax:form_list(AC))]). + + %% @doc 打印最大reductions计数, PID sort_red() -> [Pid | T] = erlang:processes(), {_, MaxVal} = erlang:process_info(Pid, reductions), Pid1 = find_max(MaxVal, T, Pid), - ?INF("max_reductions_pid:~p~n", [erlang:process_info(Pid1)]). + io:format("max_reductions_pid:~p~n", [erlang:process_info(Pid1)]). find_max(MaxVal, [TemPid | T], Pid) -> {_, TemMaxVal} = erlang:process_info(TemPid, reductions), @@ -107,62 +37,6 @@ find_max(MaxVal, [TemPid | T], Pid) -> find_max(_, [], Pid) -> Pid. -%% @doc 检测是否符合玩家id , true|false -check_roleid(RoleId) -> - <> = <>, - SvrIds = config:server_ids(), - lists:member(SvrId, SvrIds). - -%% @doc 状态转数字 -boolen2num(true) -> - ?true; -boolen2num(_) -> - ?false. - -%% @doc 获取当前日期和时间,相当于 elrang:localtime() -> {{Y, M, D}, {H, Mi, S}} -local_time() -> - UnixTime = unixtime(), - unixtime_to_localtime(UnixTime). - -%% @doc 计算距离日期时间(秒) -%% @spec calc_week_sec(WeekTime) -> TimeSec -%% where WeekTime = {Week, Time} ; Week=int() ; Time={hour, minute, second} -calc_week_sec(WeekTime) -> - CurrWeek = get_day_of_week(), - {_, Time} = local_time(), - calc_week_sec({CurrWeek, Time}, WeekTime). - -calc_week_sec({CurrWeek, CurrTime}, {TarWeek, TarTime}) -> - CurrSec = calendar:time_to_seconds(CurrTime), - TarSec = calendar:time_to_seconds(TarTime), - DiffDay = week_diff_day(CurrWeek, TarWeek), - case CurrWeek =:= TarWeek of - true -> - case CurrSec >= TarSec of - true -> - 7 * 86400 - CurrSec + TarSec; - _ -> - TarSec - CurrSec - end; - _ -> - DiffDay * 86400 - CurrSec + TarSec - end. - -%% @doc 检测是否小于指定时间 -%% under_week_time(A, B) -> true|false -%% A 是否小于 B -under_week_time({Week1, _}, {Week2, _}) when Week1 < Week2 -> - true; -under_week_time({Week1, Time1}, {Week1, Time2}) -> - TimeSec1 = calendar:time_to_seconds(Time1), - TimeSec2 = calendar:time_to_seconds(Time2), - TimeSec1 < TimeSec2; -under_week_time(_, _) -> - false. - -%% @doc 字符串转义 ' => \\' -escape(Str) -> - re:replace(Str, "'", "\\\\'", [global, {return, list}]). %% @doc 插入到数组尾部 insert_last(List, Info) when is_list(List) -> @@ -194,238 +68,6 @@ upset_list_loop(Len, List, L) when Len > 0 -> upset_list_loop(_, _, L) -> L. -%% @doc 两个时间的间隔(秒) -time_diff_sec(Time1, Time2) -> - Time1Sec = calendar:time_to_seconds(Time1), - Time2Sec = calendar:time_to_seconds(Time2), - max(0, Time2Sec - Time1Sec). - -%% @doc 删除指定定时器 -del_timer_ref(TimerRef) when is_reference(TimerRef) -> - erlang:cancel_timer(TimerRef); -del_timer_ref(_) -> - ok. - -%% @doc 距离指定星期多少天 -week_diff_day(Curr, List) when is_list(List) -> - week_diff_day(Curr, List, 0); -week_diff_day(Curr, Tar) -> - week_diff_day(Curr, [Tar]). - -week_diff_day(Curr, [TarWeek | _T], _Min) when TarWeek >= Curr -> - TarWeek - Curr; -week_diff_day(Curr, [TarWeek | T], Min) -> - case TarWeek < Min of - true -> - week_diff_day(Curr, T, TarWeek); - _ -> - week_diff_day(Curr, T, Min) - end; -week_diff_day(Curr, [], Min) -> - case Min > 0 of - true -> - 7 - Curr + Min; - _ -> - 1 - end. - -%% @spec next_sec(Time) -> Sec -%% where Time =:= {hour, min, sec}, Sec =:= integer() -%% @doc 判断时间间隔 -next_sec(Time) -> - OpenTimeSec = calendar:time_to_seconds(Time), - {_, NowTime} = local_time(), - NowTimeSec = calendar:time_to_seconds(NowTime), - case NowTimeSec < OpenTimeSec of - true -> - OpenTimeSec - NowTimeSec; - _ -> - (?ONE_DAY_SECONDS - NowTimeSec) + OpenTimeSec - end. - -%% @doc 快速排序 -quick_sort([X | L], Keys) -> - {L1, L2} = sort_helper(L, X, Keys, [], []), - quick_sort(L1, Keys) ++ [X] ++ quick_sort(L2, Keys); -quick_sort([], _) -> []. - -%% 辅助函数 -sort_helper([H | L], X, Keys, L1, L2) -> - case match_sort(Keys, X, H) of - true -> - sort_helper(L, X, Keys, [H | L1], L2); - _ -> - sort_helper(L, X, Keys, L1, [H | L2]) - end; -sort_helper([], _, _, L1, L2) -> {L1, L2}. - -%% @doc 计算顺序 -match_sort([{Index, Flag} | T], X1, X2) -> - Val1 = element(Index, X1), - Val2 = element(Index, X2), - if - Val1 > Val2 -> - Flag =< ?false; - Val1 < Val2 -> - Flag > ?false; - true -> - match_sort(T, X1, X2) - end; -match_sort([], _, _) -> - false. - -%%@doc 检测等级和转数是否符合 -check_round_level(Lv, ReLv, Round, ReRound) -> - case ReRound > 0 of - true -> - Round >= ReRound; - _ -> - Lv >= ReLv - end. - -%% @doc 是否是合服 -is_merge() -> - MergeSec = merge_time(), - OpenSec = open_time(), - OpenSec < MergeSec. - -%% @doc 获取合服天数 -merge_day() -> - case is_merge() of - true -> - MergeDate = config:merge_date(), - MergeTime = {MergeDate, {0, 0, 0}}, - {CurrDate, _} = local_time(), - NowTime = {CurrDate, {0, 0, 0}}, - {DiffDay, _} = calendar:time_difference(MergeTime, NowTime), - max(1, DiffDay + 1); - _ -> - 0 - end. - -%% @doc 获取开服时间戳 -open_time() -> - OpenDate = config:open_date(), - OpenTime = {OpenDate, {0, 0, 0}}, - datetime_to_seconds(OpenTime). - -%% @doc 获取合服时间戳 -merge_time() -> - MergeDate = config:merge_date(), - MergeTime = {MergeDate, {0, 0, 0}}, - datetime_to_seconds(MergeTime). - -%% @doc 获取开服天数 -open_day() -> - Date = config:open_date(), - OpenTime = {Date, {0, 0, 0}}, - {CurrDate, _} = local_time(), - NowTime = {CurrDate, {0, 0, 0}}, - {DiffDay, _} = calendar:time_difference(OpenTime, NowTime), - max(1, DiffDay + 1). - -%% @doc 拼凑日期数2017.1.2=>20170102 -localtime2date() -> - {Date, _} = local_time(), - localtime2date(Date). - -localtime2date({Y, M, D}) -> - Str = io_lib:format("~w~2..0w~2..0w", [Y, M, D]), - Str1 = lists:flatten(Str), - list_to_integer(Str1). - -%% @doc 随机机器人名称 -robot_name() -> - Max = data_robotname:get_max(), - HitNum = util:random(1, Max), - data_robotname:get(HitNum). - -%% @doc 整数列表转字符串==> [1,2,3] => "1,2,3" -parse_idstr(Ids) -> - parse_idstr(Ids, []). - -parse_idstr([H | T], L) -> - StrH = - case T of - [] -> - to_list(H); - _ -> - "," ++ to_list(H) - end, - parse_idstr(T, StrH ++ L); -parse_idstr([], L) -> - L. - -%% @doc 拼凑CDKEY -make_cdkey(Key, Num) when Num > 0 -> - CDkEY = Key ++ md5(lists:concat([?MIL_NOW, Num])), - ?PRINT("~s~n", [CDkEY]), - make_cdkey(Key, Num - 1); -make_cdkey(_, _) -> - ok. - -%% @doc 判断两个时间戳是否不是同一天 -other_day(Time1, Time2) -> - {Date1, _} = unixtime_to_localtime(Time1), - {Date2, _} = unixtime_to_localtime(Time2), - Date1 =/= Date2. - -%% Unix时间转换成对应的Erlang时间 -%% 返回 Now = {MegaSecs, Secs, _MicroSecs} Erlang时间 -unixtime_to_now(UnixTime) -> - M = UnixTime div 1000000, - S = UnixTime rem 1000000, - {M, S, 0}. - -%% Unix时间转换成对应的Localtime时间 -%% 返回 LocalTime = {Date, Time} Localtime时间 -unixtime_to_localtime(UnixTime) -> - Now = unixtime_to_now(UnixTime), - calendar:now_to_local_time(Now). - -%% 获取今天是星期几 -get_day_of_week() -> - NowTime = unixtime(), - get_day_of_week(NowTime). - -%% 获取指定的Unix时间是星期几 -get_day_of_week(UnixTime) -> - {Date, _Time} = unixtime_to_localtime(UnixTime), - calendar:day_of_the_week(Date). - -%% 获取当天0点到现在的秒数 -get_secs_from_midnight() -> - NowTime = unixtime(), - get_secs_from_midnight(NowTime). - -%% 获取指定的Unix时间当天0点到当时的秒数 -get_secs_from_midnight(UnixTime) -> - {{_Year, _Month, _Day}, Time} = unixtime_to_localtime(UnixTime), - calendar:time_to_seconds(Time). - -%% @doc 获取指定时间距离当天0点的秒数 -time_to_seconds(Time) -> - calendar:time_to_seconds(Time). - -%% @doc 检测两个字符串是否相等 -same_str(Str1, Str2) -> - TemStr1 = - case is_binary(Str1) of - true -> - binary_to_list(Str1); - _ -> - Str1 - end, - TemStr2 = - case is_binary(Str2) of - true -> - binary_to_list(Str2); - _ -> - Str2 - end, - TemStr1 =:= TemStr2. - - %% @doc 去除字符串左右空格 rm_str_lr_space(String) -> String1 = rm_str_lr_space1(String), @@ -449,80 +91,6 @@ rm_str_space([H | T], L) -> rm_str_space([], L) -> lists:reverse(L). -%% @doc 检测名称长度 -check_name_length(Name) -> - case lists:member(32, Name) of - true -> - {error, ?GMSG(svrmsg_10001)}; - _ -> - case unicode:characters_to_list(list_to_binary(Name)) of - {error, _, _Reason} -> - %%非法字符 - {error, ?GMSG(svrmsg_10001)}; - CharList -> - CharList1 = re:replace(CharList, "[\x{00010000}-\x{0010ffff}]", "", [{return, list}, global, unicode]),%过滤4字节的字符 - case CharList1 =:= CharList of - true -> - Len = util:string_width(CharList1), - case Len < 15 andalso Len > 2 of - true -> - true; - _ -> - %%名称长度为2~6个汉字 - {error, ?GMSG(svrmsg_10002)} - end; - _ -> - {error, ?GMSG(svrmsg_10001)} - end - end - end. - -%% 转换其他类型为list -to_list(X) when is_integer(X) -> integer_to_list(X); -to_list(X) when is_float(X) -> float_to_list(X); -to_list(X) when is_atom(X) -> atom_to_list(X); -to_list(X) when is_binary(X) -> binary_to_list(X); -to_list(X) when is_tuple(X) -> tuple_to_list(X); -to_list(X) when is_list(X) -> X. - -%% @doc 获取最高的服务器ID -get_max_svrid() -> - SvrIds = config:server_ids(), - lists:max(SvrIds). - -%% @doc %% @spec bitstring_to_obj(String::list()) -> term() -%% @doc bitstring转换为term -bitstring_to_obj(BitObj) -> - case catch bitstring_to_term(BitObj) of - {ok, Obj} -> - Obj; - _ -> - to_list(BitObj) - end. - -%% @spec bitstring_to_term(String::list()) -> {error, Why::term()} | {ok, term()} -%% @doc term反序列化,bitstring转换为term -bitstring_to_term(undefined) -> {ok, undefined}; -bitstring_to_term(BitString) -> string_to_term(binary_to_list(BitString)). - -%% @spec string_to_term(String::list()) -> {error, Why::term()} | {ok, term()} -%% @doc term反序列化,string转换为term,e.g., "[{a},1]" => [{a},1] -string_to_term(String) -> - case erl_scan:string(String ++ ".") of - {ok, Tokens, _} -> - erl_parse:parse_term(Tokens); - {error, Err, _} -> {error, Err}; - Err -> {error, Err} - end. - -%% term序列化,term转换为string格式,e.g., [{a},1] => "[{a},1]" -term_to_string(Term) -> - binary_to_list(list_to_binary(io_lib:format("~p", [Term]))). - -%% term序列化,term转换为bitstring格式,e.g., [{a},1] => <<"[{a},1]">> -term_to_bitstring(Term) -> - erlang:list_to_bitstring(io_lib:format("~p", [Term])). - %% @doc 随机列表 rand_list([Obj]) -> Obj; @@ -536,48 +104,6 @@ rand_list(L) -> false end. -%% @doc 安全创建ets,不抛任何异常~~ -safe_create_ets(Name, Args) -> - try - case ets:info(Name) of - undefined -> - ets:new(Name, Args); - _ -> %%已经存在就不重复创建了 - Name - end - catch _:EM -> - ?ERR("safe_create_ets(~p,~p) exception ~p", [Name, Args, EM]), - false - end. - -%% @doc 三目运算 -ifelse(A, B, C) -> - case A of - true -> - B; - _ -> - C - end. - -%% @doc 获取unix时间戳 -unixtime() -> - {MegaSecs, Secs, _MicroSecs} = os:timestamp(), - MegaSecs * 1000000 + Secs. - -longunixtime() -> - {A, B, C} = os:timestamp(), - A * 1000000000 + B * 1000 + C div 1000. - -%%========================================================================= -%% 列表操作 -%%========================================================================= - -make_sign(Accid, Accname) -> - TICKET = config:get_ticket(), - Tstamp = unixtime(), - Hex = md5(lists:concat([Accid, Accname, Tstamp, TICKET])), - {Tstamp, Hex}. - %% 随机取出list元素 list_rand([]) -> null; list_rand(List) -> @@ -844,26 +370,6 @@ filter_text_gm(Text) when is_bitstring(Text) -> filter_text_gm(Text) when is_list(Text) -> list_to_bitstring(Text). -%% 敏感词过滤 -%% @param Text list() | bitstring() -%% @return bitstring() 过滤后的文本 -filter_text(Text, Lv) when is_bitstring(Text) -> - S = bitstring_to_list(Text), - filter_text(S, Lv); -filter_text(Text, Lv) when is_list(Text) -> - [Term] = io_lib:format("~ts", [Text]), - svr_word:replace_sensitive_talk(Term, Lv). - -%% 名字过滤 -%% @param Text list() | bitstring() -%% @return bitstring() 过滤后的文本 -filter_name(Text) when is_bitstring(Text) -> - S = bitstring_to_list(Text), - filter_name(S); -filter_name(Text) when is_list(Text) -> - [Term] = io_lib:format("~ts", [Text]), - svr_word:replace_sensitive_name(Term). - %% 敏感词检测 %% @return true 存在关键词 %% false 不存在关键词 @@ -933,7 +439,6 @@ filter_string(String, CharList) -> ResultString = filter_string_helper(binary_to_list(String), CharList, []), list_to_binary(ResultString); false -> - ?ERR("filter_string: Error string=[~w]", [String]), String end. @@ -945,92 +450,6 @@ filter_string_helper([H | T], CharList, ResultString) -> false -> filter_string_helper(T, CharList, ResultString ++ [H]) end. -%%========================================================================= -%% 其他操作 -%%========================================================================= - -%% 产生一个介于Min到Max之间的随机整数 -random(Same, Same) -> Same; -random(Min, Max) when Max < Min -> 0; -random(Min, Max) -> - %% 以保证不同进程都可取得不同的种子 - case get("rand_seed") of - undefined -> - rand:seed(exs64, os:timestamp()), - put("rand_seed", 1); - _ -> skip - end, - M = Min - 1, - if - Max - M =< 0 -> 0; - true -> rand:uniform(Max - M) + M - end. - -%% 向上取整 -ceil(N) -> - T = trunc(N), - case N == T of - true -> T; - false -> 1 + T - end. - -%% 向下取整 -floor(X) -> - T = trunc(X), - case (X < T) of - true -> T - 1; - _ -> T - end. - -%% 睡眠 -sleep(T) -> - receive - after T -> ok - end. - -sleep(T, F) -> - receive - after T -> F() - end. - -%% 获取客户端ip -get_ip(Socket) -> - case catch inet:peername(Socket) of - {ok, {Ip, _Port}} -> - Ip; - _ -> - case catch ssl:peername(Socket) of - {ok, {Ip, _Port}} -> - Ip; - _ -> - {0, 0, 0, 0} - end - end. - -%%计数器 -counter(Type) -> - counter(Type, 1). -counter(Type, Inc) -> - ets:update_counter(ets_counter, Type, Inc). - -%% 获取运营服ID -get_server_id() -> - Server = case application:get_env(game, card_server) of - {ok, [_Ser]} -> _Ser; - _ -> "" - end, - %{ok, [Server]} = application:get_env(card_server), - Len = string:len(Server), - case Len > 1 of - true -> - ServerId = string:sub_string(Server, 2, Len), - case string:to_integer(ServerId) of - {Id, _} -> Id; - _ -> 0 - end; - false -> - 0 - end. %% 显示record %% 用法 : r2p(#ets_online{...}, record_info(fields, ets_online)) @@ -1135,48 +554,6 @@ process_infos() -> end, [Fun(erlang:process_info(P)) || P <- erlang:processes()]. -cn(Data) -> - io:format("~ts~n", [Data]). - -%% @spec datetime_to_seconds(DateTime) -> false | SecondsTime -%% DateTime = {{2011,11,15},{16,14,57}} = {{Y, M, D}, {h, m, s}} -%% @doc 将日期转换unix时间戳 -datetime_to_seconds(0) -> 0; -datetime_to_seconds(DateTime) -> - case calendar:local_time_to_universal_time_dst(DateTime) of - [] -> false; - [_, Udate] -> - calendar:datetime_to_gregorian_seconds(Udate) - 719528 * 24 * 3600; - [Udate] -> - calendar:datetime_to_gregorian_seconds(Udate) - 719528 * 24 * 3600 - end. - -%% @doc 重新定向中央服务器 -redirect_center(NodeName, Cookie) -> - case svr_node_kf:get_node_id() =:= 0 of - true -> - case nodes(hidden) of - [] -> - ok; - Nodes -> - F = fun(TemNodeName) -> - catch rpc:call(TemNodeName, svr_kfcenter, del_node, [node()]), - net_kernel:disconnect(TemNodeName) - end, - [F(TemNodeName) || TemNodeName <- Nodes] - end, - erlang:set_cookie(NodeName, Cookie), - case net_adm:ping(NodeName) of - pong -> - Sql = io_lib:format(<<"replace into base_kf(`id`,`name`,`cookie`) values(~p, ~p, '~p')">>, [100, NodeName, Cookie]), - db:execute_nohalt(Sql); - _ -> - ok - end; - _ -> - ok - end. - %% @doc 检测是否在范围内 check_range(X, Y, TarX, TarY, Range) -> X1 = abs(X - TarX), diff --git a/src/srvNodeMgr/tools/gameWorld/test/misc/config.erl b/src/srvNodeMgr/tools/gameWorld/test/misc/config.erl deleted file mode 100644 index dbc4f1d..0000000 --- a/src/srvNodeMgr/tools/gameWorld/test/misc/config.erl +++ /dev/null @@ -1,332 +0,0 @@ --module(config). --include("record.hrl"). --include("common.hrl"). --include_lib("stdlib/include/ms_transform.hrl"). - --compile(export_all). - -%% 获取 .config里的配置信息 -get_log_path(App) -> - case application:get_env(App, log_path) of - {ok, LogPath} -> LogPath; - _ -> "logs" - end. - -%% 获取 .config里的配置信息 -get_log_level(App) -> - case application:get_env(App, log_level) of - {ok, LogLevel} -> LogLevel; - _ -> 3 - end. - -%% 获取 .config里的配置信息 -get_server_node(App) -> - case application:get_env(App, game_server_node) of - {ok, Node} -> Node; - _ -> '' - end. -%% 获取平台重置的key -get_charge_key(App) -> - case application:get_env(App, charge_key) of - {ok, Node} -> Node; - _ -> '' - end. - -%% 获取 .config里的配置信息 -get_md5_key(App) -> - case application:get_env(App, md5_key) of - {ok, Node} -> Node; - _ -> '' - end. - -%% 获取 .config里的配置信息 -get_platform_key(App) -> - case application:get_env(App, platform_key) of - {ok, Node} -> Node; - _ -> '' - end. - -get_infant_ctrl(App) -> -%% 防沉迷开关读取 - case application:get_env(App, infant_ctrl) of - {ok, Mode} -> tool:to_integer(Mode); - _ -> 0 - end. - -get_tcp_listener(App) -> - case application:get_env(App, tcp_listener) of - {ok, false} -> throw(undefined); - {ok, Tcp_listener} -> - try - {_, Port} = lists:keyfind(port, 1, Tcp_listener), - {_, Acceptor_num} = lists:keyfind(acceptor_num, 1, Tcp_listener), - {_, Max_connections} = lists:keyfind(max_connections, 1, Tcp_listener), - [Port, Acceptor_num, Max_connections] - catch - _:_ -> exit({bad_config, {server, {tcp_listener, config_error}}}) - end; - undefined -> throw(undefined) - end. - -get_tcp_listener_ip(App) -> - case application:get_env(App, tcp_listener_ip) of - {ok, false} -> throw(undefined); - {ok, Tcp_listener_ip} -> - try - {_, Ip} = lists:keyfind(ip, 1, Tcp_listener_ip), - [Ip] - catch - _:_ -> exit({bad_config, {server, {tcp_listener, config_error}}}) - end; - undefined -> throw(undefined) - end. - -get_mysql_config(App) -> - case application:get_env(App, mysql_config) of - {ok, false} -> throw(undefined); - {ok, Mysql_config} -> - {_, Host} = lists:keyfind(host, 1, Mysql_config), - {_, Port} = lists:keyfind(port, 1, Mysql_config), - {_, User} = lists:keyfind(user, 1, Mysql_config), - {_, Password} = lists:keyfind(password, 1, Mysql_config), - {_, DB} = lists:keyfind(db, 1, Mysql_config), - {_, Encode} = lists:keyfind(encode, 1, Mysql_config), - {_, Conns} = lists:keyfind(conns, 1, Mysql_config), - [Host, Port, User, Password, DB, Encode, Conns]; - undefined -> throw(undefined) - end. - -get_mysql_log_config(App) -> - case application:get_env(App, mysql_log_config) of - {ok, false} -> throw(undefined); - {ok, Mysql_config} -> - {_, Host} = lists:keyfind(host, 1, Mysql_config), - {_, Port} = lists:keyfind(port, 1, Mysql_config), - {_, User} = lists:keyfind(user, 1, Mysql_config), - {_, Password} = lists:keyfind(password, 1, Mysql_config), - {_, DB} = lists:keyfind(db, 1, Mysql_config), - {_, Encode} = lists:keyfind(encode, 1, Mysql_config), - {_, Conns} = lists:keyfind(conns, 1, Mysql_config), - [Host, Port, User, Password, DB, Encode, Conns]; - undefined -> throw(undefined) - end. - -get_mongo_config(App) -> - case application:get_env(App, emongo_config) of - {ok, false} -> throw(undefined); - {ok, Emongo_config} -> - {_, PoolId} = lists:keyfind(poolId, 1, Emongo_config), - {_, EmongoSize} = lists:keyfind(emongoSize, 1, Emongo_config), - {_, EmongoHost} = lists:keyfind(emongoHost, 1, Emongo_config), - {_, EmongoPort} = lists:keyfind(emongoPort, 1, Emongo_config), - {_, EmongoDatabase} = lists:keyfind(emongoDatabase, 1, Emongo_config), - [PoolId, EmongoHost, EmongoPort, EmongoDatabase, EmongoSize]; - undefined -> throw(undefined) - end. - -get_slave_mongo_config(App) -> - case application:get_env(App, slave_emongo_config) of - {ok, false} -> throw(undefined); - {ok, Emongo_config} -> - {_, PoolId} = lists:keyfind(poolId, 1, Emongo_config), - {_, EmongoSize} = lists:keyfind(emongoSize, 1, Emongo_config), - {_, EmongoHost} = lists:keyfind(emongoHost, 1, Emongo_config), - {_, EmongoPort} = lists:keyfind(emongoPort, 1, Emongo_config), - {_, EmongoDatabase} = lists:keyfind(emongoDatabase, 1, Emongo_config), - [PoolId, EmongoHost, EmongoPort, EmongoDatabase, EmongoSize]; - undefined -> get_mongo_config(App) - end. - -has_slave_mongo_config() -> - case application:get_env(server, slave_emongo_config) of - {ok, false} -> false; - {ok, _Emongo_config} -> true - end. - -get_read_data_mode(App) -> - case application:get_env(App, base_data_from_db) of - {ok, Mode} -> tool:to_integer(Mode); - _ -> 0 - end. - -get_gateway_node(App) -> - case application:get_env(App, gateway_node) of - {ok, Gateway_node} -> Gateway_node; - _ -> undefined - end. - -get_gateway_async_time() -> - case application:get_env(gateway, gateway_async_time) of - {ok, Async_time} -> Async_time; - _ -> undefined - end. - - -get_scene_here(App) -> - case application:get_env(App, scene_here) of - undefined -> []; - {ok, all} -> - MS = ets:fun2ms(fun(S) when S#temp_scene.type =< 3 -> S#temp_scene.sid end), - ets:select(?ETS_TEMP_SCENE, MS); - {ok, SL} when is_list(SL) -> - SL1 = lists:filter(fun(SId) -> - case ets:lookup(?ETS_TEMP_SCENE, SId) of - [] -> false; - [S] -> - if S#temp_scene.type =< 3 -> - true; - true -> - false - end - end - end, - SL), - SL1; - _ -> [] - end. - -get_guest_account_url(App) -> - case application:get_env(App, guest_account_url) of - {ok, Guest_account_url} -> Guest_account_url; - _ -> "" - end. - -%% GM指令开关读取 -get_can_gmcmd() -> - case application:get_env(server, can_gmcmd) of - {ok, Mode} -> tool:to_integer(Mode); - _ -> throw(undefined) - end. - -get_strict_md5(App) -> - case application:get_env(App, strict_md5) of - {ok, Strict_md5} -> Strict_md5; - _ -> 1 - end. - -get_http_ips(App) -> - case application:get_env(App, http_ips) of - {ok, Http_ips} -> Http_ips; - _ -> [] - end. - -%% 获取 .config里的配置信息 -get_server_number(App) -> - case application:get_env(App, server_number) of - {ok, Server_number} -> - case is_integer(Server_number) == true of - false -> 0; - true -> Server_number - end; - _ -> 0 - end. - -%% 获取 .config里的配置信息 -get_max_id(App) -> - case application:get_env(App, max_id) of - {ok, Max_id} -> - case is_integer(Max_id) == true of - false -> 0; - true -> Max_id - end; - _ -> 0 - end. - -%% 获取平台名称 -get_platform_name() -> - case application:get_env(server, platform) of - {ok, Name} -> - Name; - _ -> - undefined - end. -%% 获取加密串号 -get_card_key() -> - case application:get_env(server, card_key) of - {ok, Crypto} -> - Crypto; - _ -> - undefined - end. - -%% 获取服号 -get_server_num() -> - case application:get_env(server, server_num) of - {ok, N} -> - N; - _ -> - undefined - end. - -%%获取数据库日志路径 -get_db_log_path() -> - case application:get_env(server, db_log_path) of - {ok, N} -> - N; - _ -> - undefined - end. - -%%获取开服时间 -get_opening_time() -> - case application:get_env(server, open_time) of - {ok, N} -> - N; - _ -> - 0 - end. - - -%%获取节点1的id -get_domain() -> - case application:get_env(server, domain) of - {ok, N} -> - N; - _ -> - 1 - end. - - -%%获取节点2的id -get_node_id_2() -> - case application:get_env(server, node_id_2) of - {ok, N} -> - N; - _ -> - 2 - end. - -%%获取客户端操作系统 -get_client_os(Os) -> - case Os of - 1 -> - <<"Android">>; - 2 -> - <<"iphone">>; - _ -> - <<"未知">> - end. -%%获取客户端设备类型 -get_client_device_type(DeviceType) -> - case DeviceType of - 1 -> <<"Android">>; - 2 -> <<"iphone">>; - 3 -> <<"ipad">>; - _ -> <<"未知">> - end. -%%获取客户端移动网络类型 -get_client_isp(Isp) -> - case Isp of - 1 -> <<"中国移动">>; - 2 -> <<"中国电信">>; - 3 -> <<"中国联通">>; - _ -> "未知" - end. -%%获取客户端上网方式 -get_client_net_type(Net) -> - case Net of - 1 -> <<"3G">>; - 2 -> <<"WIFI">>; - 3 -> <<"2G">>; - _ -> <<"未知">> - end. \ No newline at end of file diff --git a/src/srvNodeMgr/tools/gameWorld/test/misc/dynamic_compile.erl b/src/srvNodeMgr/tools/gameWorld/test/misc/dynamic_compile.erl deleted file mode 100644 index e25e691..0000000 --- a/src/srvNodeMgr/tools/gameWorld/test/misc/dynamic_compile.erl +++ /dev/null @@ -1,270 +0,0 @@ -%% Copyright (c) 2007 -%% Mats Cronqvist -%% Chris Newcombe -%% Jacob Vorreuter -%% -%% Permission is hereby granted, free of charge, to any person -%% obtaining a copy of this software and associated documentation -%% files (the "Software"), to deal in the Software without -%% restriction, including without limitation the rights to use, -%% copy, modify, merge, publish, distribute, sublicense, and/or sell -%% copies of the Software, and to permit persons to whom the -%% Software is furnished to do so, subject to the following -%% conditions: -%% -%% The above copyright notice and this permission notice shall be -%% included in all copies or substantial portions of the Software. -%% -%% THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -%% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -%% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -%% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -%% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -%% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -%% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -%% OTHER DEALINGS IN THE SOFTWARE. - -%%%------------------------------------------------------------------- -%%% File : dynamic_compile.erl -%%% Description : -%%% Authors : Mats Cronqvist -%%% Chris Newcombe -%%% Jacob Vorreuter -%%% - add support for limit include-file depth (and prevent circular references) -%%% prevent circular macro expansion set FILE correctly when -module() is found -%%% -include_lib support $ENVVAR in include filenames -%%% substitute-stringize (??MACRO) -%%% -undef/-ifdef/-ifndef/-else/-endif -%%% -file(File, Line) -%%%------------------------------------------------------------------- --module(dynamic_compile). - -%% API --export([from_string/1, from_string/2]). - --import(lists, [reverse/1, keyreplace/4]). - -%%==================================================================== -%% API -%%==================================================================== -%%-------------------------------------------------------------------- -%% Function: -%% Description: -%% Returns a binary that can be used with -%% code:load_binary(Module, ModuleFilenameForInternalRecords, Binary). -%%-------------------------------------------------------------------- -from_string(CodeStr) -> - from_string(CodeStr, []). - -% takes Options as for compile:forms/2 -from_string(CodeStr, CompileFormsOptions) -> - %% Initialise the macro dictionary with the default predefined macros, - %% (adapted from epp.erl:predef_macros/1 - Filename = "compiled_from_string", - %%Machine = list_to_atom(erlang:system_info(machine)), - Ms0 = dict:new(), - % Ms1 = dict:store('FILE', {[], "compiled_from_string"}, Ms0), - % Ms2 = dict:store('LINE', {[], 1}, Ms1), % actually we might add special code for this - % Ms3 = dict:store('MODULE', {[], undefined}, Ms2), - % Ms4 = dict:store('MODULE_STRING', {[], undefined}, Ms3), - % Ms5 = dict:store('MACHINE', {[], Machine}, Ms4), - % InitMD = dict:store(Machine, {[], true}, Ms5), - InitMD = Ms0, - - %% From the docs for compile:forms: - %% When encountering an -include or -include_dir directive, the compiler searches for header files in the following directories: - %% 1. ".", the current working directory of the file server; - %% 2. the base name of the compiled file; - %% 3. the directories specified using the i option. The directory specified last is searched first. - %% In this case, #2 is meaningless. - IncludeSearchPath = ["." | reverse([Dir || {i, Dir} <- CompileFormsOptions])], - {RevForms, _OutMacroDict} = scan_and_parse(CodeStr, Filename, 1, [], InitMD, IncludeSearchPath), - Forms = reverse(RevForms), - - %% note: 'binary' is forced as an implicit option, whether it is provided or not. - case compile:forms(Forms, CompileFormsOptions) of - {ok, ModuleName, CompiledCodeBinary} when is_binary(CompiledCodeBinary) -> - {ModuleName, CompiledCodeBinary}; - {ok, ModuleName, CompiledCodeBinary, []} when is_binary(CompiledCodeBinary) -> % empty warnings list - {ModuleName, CompiledCodeBinary}; - {ok, _ModuleName, _CompiledCodeBinary, Warnings} -> - throw({?MODULE, warnings, Warnings}); - Other -> - throw({?MODULE, compile_forms, Other}) - end. - -%%==================================================================== -%% Internal functions -%%==================================================================== -%%% Code from Mats Cronqvist -%%% See http://www.erlang.org/pipermail/erlang-questions/2007-March/025507.html -%%%## 'scan_and_parse' -%%% -%%% basically we call the OTP scanner and parser (erl_scan and -%%% erl_parse) line-by-line, but check each scanned line for (or -%%% definitions of) macros before parsing. -%% returns {ReverseForms, FinalMacroDict} -scan_and_parse([], _CurrFilename, _CurrLine, RevForms, MacroDict, _IncludeSearchPath) -> - {RevForms, MacroDict}; - -scan_and_parse(RemainingText, CurrFilename, CurrLine, RevForms, MacroDict, IncludeSearchPath) -> - case scanner(RemainingText, CurrLine, MacroDict) of - {tokens, NLine, NRemainingText, Toks} -> - {ok, Form} = erl_parse:parse_form(Toks), - scan_and_parse(NRemainingText, CurrFilename, NLine, [Form | RevForms], MacroDict, IncludeSearchPath); - {macro, NLine, NRemainingText, NMacroDict} -> - scan_and_parse(NRemainingText, CurrFilename, NLine, RevForms, NMacroDict, IncludeSearchPath); - {include, NLine, NRemainingText, IncludeFilename} -> - IncludeFileRemainingTextents = read_include_file(IncludeFilename, IncludeSearchPath), - %%io:format("include file ~p contents: ~n~p~nRemainingText = ~p~n", [IncludeFilename,IncludeFileRemainingTextents, RemainingText]), - %% Modify the FILE macro to reflect the filename - %%IncludeMacroDict = dict:store('FILE', {[],IncludeFilename}, MacroDict), - IncludeMacroDict = MacroDict, - - %% Process the header file (inc. any nested header files) - {RevIncludeForms, IncludedMacroDict} = scan_and_parse(IncludeFileRemainingTextents, IncludeFilename, 1, [], IncludeMacroDict, IncludeSearchPath), - %io:format("include file results = ~p~n", [R]), - %% Restore the FILE macro in the NEW MacroDict (so we keep any macros defined in the header file) - %%NMacroDict = dict:store('FILE', {[],CurrFilename}, IncludedMacroDict), - NMacroDict = IncludedMacroDict, - - %% Continue with the original file - scan_and_parse(NRemainingText, CurrFilename, NLine, RevIncludeForms ++ RevForms, NMacroDict, IncludeSearchPath); - done -> - scan_and_parse([], CurrFilename, CurrLine, RevForms, MacroDict, IncludeSearchPath) - end. - -scanner(Text, Line, MacroDict) -> - case erl_scan:tokens([], Text, Line) of - {done, {ok, Toks, NLine}, LeftOverChars} -> - case pre_proc(Toks, MacroDict) of - {tokens, NToks} -> {tokens, NLine, LeftOverChars, NToks}; - {macro, NMacroDict} -> {macro, NLine, LeftOverChars, NMacroDict}; - {include, Filename} -> {include, NLine, LeftOverChars, Filename} - end; - {more, _Continuation} -> - %% This is supposed to mean "term is not yet complete" (i.e. a '.' has - %% not been reached yet). - %% However, for some bizarre reason we also get this if there is a comment after the final '.' in a file. - %% So we check to see if Text only consists of comments. - case is_only_comments(Text) of - true -> - done; - false -> - throw({incomplete_term, Text, Line}) - end - end. - -is_only_comments(Text) -> is_only_comments(Text, not_in_comment). - -is_only_comments([], _) -> true; -is_only_comments([$ | T], not_in_comment) -> - is_only_comments(T, not_in_comment); % skipping whitspace outside of comment -is_only_comments([$\t | T], not_in_comment) -> - is_only_comments(T, not_in_comment); % skipping whitspace outside of comment -is_only_comments([$\n | T], not_in_comment) -> - is_only_comments(T, not_in_comment); % skipping whitspace outside of comment -is_only_comments([$% | T], not_in_comment) -> is_only_comments(T, in_comment); % found start of a comment -is_only_comments(_, not_in_comment) -> false; -% found any significant char NOT in a comment -is_only_comments([$\n | T], in_comment) -> is_only_comments(T, not_in_comment); % found end of a comment -is_only_comments([_ | T], in_comment) -> is_only_comments(T, in_comment). % skipping over in-comment chars - -%%%## 'pre-proc' -%%% -%%% have to implement a subset of the pre-processor, since epp insists -%%% on running on a file. -%%% only handles 2 cases; -%% -define(MACRO, something). -%% -define(MACRO(VAR1,VARN),{stuff,VAR1,more,stuff,VARN,extra,stuff}). -pre_proc([{'-', _}, {atom, _, define}, {'(', _}, {_, _, Name} | DefToks], MacroDict) -> - false = dict:is_key(Name, MacroDict), - case DefToks of - [{',', _} | Macro] -> - {macro, dict:store(Name, {[], macro_body_def(Macro, [])}, MacroDict)}; - [{'(', _} | Macro] -> - {macro, dict:store(Name, macro_params_body_def(Macro, []), MacroDict)} - end; - -pre_proc([{'-', _}, {atom, _, include}, {'(', _}, {string, _, Filename}, {')', _}, {dot, _}], _MacroDict) -> - {include, Filename}; - -pre_proc(Toks, MacroDict) -> - {tokens, subst_macros(Toks, MacroDict)}. - -macro_params_body_def([{')', _}, {',', _} | Toks], RevParams) -> - {reverse(RevParams), macro_body_def(Toks, [])}; -macro_params_body_def([{var, _, Param} | Toks], RevParams) -> - macro_params_body_def(Toks, [Param | RevParams]); -macro_params_body_def([{',', _}, {var, _, Param} | Toks], RevParams) -> - macro_params_body_def(Toks, [Param | RevParams]). - -macro_body_def([{')', _}, {dot, _}], RevMacroBodyToks) -> - reverse(RevMacroBodyToks); -macro_body_def([Tok | Toks], RevMacroBodyToks) -> - macro_body_def(Toks, [Tok | RevMacroBodyToks]). - -subst_macros(Toks, MacroDict) -> - reverse(subst_macros_rev(Toks, MacroDict, [])). - -%% returns a reversed list of tokes -subst_macros_rev([{'?', _}, {_, LineNum, 'LINE'} | Toks], MacroDict, RevOutToks) -> - %% special-case for ?LINE, to avoid creating a new MacroDict for every line in the source file - subst_macros_rev(Toks, MacroDict, [{integer, LineNum, LineNum}] ++ RevOutToks); - -subst_macros_rev([{'?', _}, {_, _, Name}, {'(', _} = Paren | Toks], MacroDict, RevOutToks) -> - case dict:fetch(Name, MacroDict) of - {[], MacroValue} -> - %% This macro does not have any vars, so ignore the fact that the invocation is followed by "(...stuff" - %% Recursively expand any macro calls inside this macro's value - %% TODO: avoid infinite expansion due to circular references (even indirect ones) - RevExpandedOtherMacrosToks = subst_macros_rev(MacroValue, MacroDict, []), - subst_macros_rev([Paren | Toks], MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks); - ParamsAndBody -> - %% This macro does have vars. - %% Collect all of the passe arguments, in an ordered list - {NToks, Arguments} = subst_macros_get_args(Toks, []), - %% Expand the varibles - ExpandedParamsToks = subst_macros_subst_args_for_vars(ParamsAndBody, Arguments), - %% Recursively expand any macro calls inside this macro's value - %% TODO: avoid infinite expansion due to circular references (even indirect ones) - RevExpandedOtherMacrosToks = subst_macros_rev(ExpandedParamsToks, MacroDict, []), - subst_macros_rev(NToks, MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks) - end; - -subst_macros_rev([{'?', _}, {_, _, Name} | Toks], MacroDict, RevOutToks) -> - %% This macro invocation does not have arguments. - %% Therefore the definition should not have parameters - {[], MacroValue} = dict:fetch(Name, MacroDict), - - %% Recursively expand any macro calls inside this macro's value - %% TODO: avoid infinite expansion due to circular references (even indirect ones) - RevExpandedOtherMacrosToks = subst_macros_rev(MacroValue, MacroDict, []), - subst_macros_rev(Toks, MacroDict, RevExpandedOtherMacrosToks ++ RevOutToks); - -subst_macros_rev([Tok | Toks], MacroDict, RevOutToks) -> - subst_macros_rev(Toks, MacroDict, [Tok | RevOutToks]); -subst_macros_rev([], _MacroDict, RevOutToks) -> RevOutToks. - -subst_macros_get_args([{')', _} | Toks], RevArgs) -> - {Toks, reverse(RevArgs)}; -subst_macros_get_args([{',', _}, {var, _, ArgName} | Toks], RevArgs) -> - subst_macros_get_args(Toks, [ArgName | RevArgs]); -subst_macros_get_args([{var, _, ArgName} | Toks], RevArgs) -> - subst_macros_get_args(Toks, [ArgName | RevArgs]). - -subst_macros_subst_args_for_vars({[], BodyToks}, []) -> - BodyToks; -subst_macros_subst_args_for_vars({[Param | Params], BodyToks}, [Arg | Args]) -> - NBodyToks = keyreplace(Param, 3, BodyToks, {var, 1, Arg}), - subst_macros_subst_args_for_vars({Params, NBodyToks}, Args). - -read_include_file(Filename, IncludeSearchPath) -> - case file:path_open(IncludeSearchPath, Filename, [read, raw, binary]) of - {ok, IoDevice, FullName} -> - {ok, Data} = file:read(IoDevice, filelib:file_size(FullName)), - file:close(IoDevice), - binary_to_list(Data); - {error, Reason} -> - throw({failed_to_read_include_file, Reason, Filename, IncludeSearchPath}) - end. \ No newline at end of file diff --git a/src/srvNodeMgr/tools/gameWorld/test/misc/game_alarm_handler.erl b/src/srvNodeMgr/tools/gameWorld/test/misc/game_alarm_handler.erl deleted file mode 100644 index 42854af..0000000 --- a/src/srvNodeMgr/tools/gameWorld/test/misc/game_alarm_handler.erl +++ /dev/null @@ -1,41 +0,0 @@ -%%%---------------------------------------- -%%% @Module : game_alarm_handler -%%% @Author : csj -%%% @Created : 2010.10.05 -%%% @Description: 警报 -%%%---------------------------------------- - --module(game_alarm_handler). --behaviour(gen_event). --include("common.hrl"). - -%%gen_envent callbacks. --export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, code_change/3]). - -init(Args) -> - ?DEBUG("game_alarm_handler init : ~p.", [Args]), - {ok, Args}. - -handle_event({set_alarm, From}, _State) -> - ?DEBUG("csj depot clear by ~p started.", [From]), - {ok, _State}; - -handle_event({clear_alarm, From}, _State) -> - ?DEBUG("csj depot clear by ~p done.", [From]), - {ok, _State}; - -handle_event(Event, State) -> - ?DEBUG("unmatched event: ~p.", [Event]), - {ok, State}. - -handle_call(_Req, State) -> - {ok, State, State}. - -handle_info(_Info, State) -> - {ok, State}. - -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. diff --git a/src/srvNodeMgr/tools/gameWorld/test/misc/game_timer.erl b/src/srvNodeMgr/tools/gameWorld/test/misc/game_timer.erl deleted file mode 100644 index 57d7dc4..0000000 --- a/src/srvNodeMgr/tools/gameWorld/test/misc/game_timer.erl +++ /dev/null @@ -1,131 +0,0 @@ -%%%---------------------------------------------------------------------- -%%% File : game_timer.erl -%%% Author : csj -%%% Created : 2010-10-17 -%%% Description: 时间生成器 -%%%---------------------------------------------------------------------- --module(game_timer). - --behaviour(gen_server). -%% -------------------------------------------------------------------- -%% Include files -%% -------------------------------------------------------------------- --include("common.hrl"). - -%% -------------------------------------------------------------------- -%% External exports --export([now/0, now_seconds/0, cpu_time/0, start_link/0, start/1, info/0]). - -%% gen_server callbacks --export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). - -%% ==================================================================== -%% External functions -%% ==================================================================== -now() -> - [{timer, {Now, _}}] = ets:lookup(ets_timer, timer), - Now. - -now_seconds() -> - [{timer, {Now, _}}] = ets:lookup(ets_timer, timer), - {MegaSecs, Secs, _MicroSecs} = Now, - lists:concat([MegaSecs, Secs]). - -cpu_time() -> - [{timer, {_, Wallclock_Time_Since_Last_Call}}] = ets:lookup(ets_timer, timer), - Wallclock_Time_Since_Last_Call. - -info() -> - [ - ets:info(ets_timer), - ets:tab2list(ets_timer) - ]. - --define(CLOCK, 100). - -start(Sup) -> - supervisor:start_child(Sup, - {game_timer, - {game_timer, start_link, []}, - permanent, brutal_kill, worker, [game_timer]}). - -%% ==================================================================== -%% Server functions -%% ==================================================================== -start_link() -> - gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). - -%% -------------------------------------------------------------------- -%% Function: init/1 -%% Description: Initiates the server -%% Returns: {ok, State} | -%% {ok, State, Timeout} | -%% ignore | -%% {stop, Reason} -%% -------------------------------------------------------------------- -init([]) -> - ets:new(ets_timer, [set, protected, named_table]), - ets:insert(ets_timer, {timer, {erlang:now(), 0}}), - erlang:send_after(?CLOCK, self(), {event, clock}), - misc:write_monitor_pid(self(), ?MODULE, {}), - {ok, []}. - -%% -------------------------------------------------------------------- -%% Function: handle_call/3 -%% Description: Handling call messages -%% Returns: {reply, Reply, State} | -%% {reply, Reply, State, Timeout} | -%% {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, Reply, State} | (terminate/2 is called) -%% {stop, Reason, State} (terminate/2 is called) -%% -------------------------------------------------------------------- -handle_call(_Request, _From, State) -> - {reply, State, State}. - -%% -------------------------------------------------------------------- -%% Function: handle_cast/2 -%% Description: Handling cast messages -%% Returns: {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, State} (terminate/2 is called) -%% -------------------------------------------------------------------- -handle_cast(_Msg, State) -> - {noreply, State}. - -%% -------------------------------------------------------------------- -%% Function: handle_info/2 -%% Description: Handling all non call/cast messages -%% Returns: {noreply, State} | -%% {noreply, State, Timeout} | -%% {stop, Reason, State} (terminate/2 is called) -%% -------------------------------------------------------------------- -handle_info({event, clock}, State) -> - {_Total_Run_Time, Time_Since_Last_Call} = statistics(runtime), - ets:insert(ets_timer, {timer, {erlang:now(), Time_Since_Last_Call}}), - erlang:send_after(?CLOCK, self(), {event, clock}), - {noreply, State}; - -handle_info(_Info, State) -> - {noreply, State}. - -%% -------------------------------------------------------------------- -%% Function: terminate/2 -%% Description: Shutdown the server -%% Returns: any (ignored by gen_server) -%% -------------------------------------------------------------------- -terminate(_Reason, _State) -> - misc:delete_monitor_pid(self()), - ok. - -%% -------------------------------------------------------------------- -%% Func: code_change/3 -%% Purpose: Convert process state when code is changed -%% Returns: {ok, NewState} -%% -------------------------------------------------------------------- -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -%% -------------------------------------------------------------------- -%%% Internal functions -%% -------------------------------------------------------------------- diff --git a/src/srvNodeMgr/tools/gameWorld/test/misc/logger_h.erl b/src/srvNodeMgr/tools/gameWorld/test/misc/logger_h.erl deleted file mode 100644 index 4d8af8f..0000000 --- a/src/srvNodeMgr/tools/gameWorld/test/misc/logger_h.erl +++ /dev/null @@ -1,238 +0,0 @@ -%%%---------------------------------------------------------------------- -%%% File : logger_h.erl -%%% Created : 2010-08-20 -%%%---------------------------------------------------------------------- - --module(logger_h). - --behaviour(gen_event). - --include("common.hrl"). --include("debug.hrl"). - --export([start_link/2, log_level/0]). -%% gen_event callbacks --export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, - code_change/3, reopen_log/0, rotate_log/1]). - --record(state, {fd, file, level}). --define(LOG_FILE_INTERVAL, 24 * 3600000). % 1小时新开1个log文件 - -start_link(Log_file, Log_level) -> - case gen_event:start_link({local, ?LOGMODULE}) of - Ret = {ok, _Pid} -> - gen_event:add_handler(?LOGMODULE, ?MODULE, [Log_file, Log_level]), - Ret; - Other -> - Other - end. - -log_level() -> - gen_event:call({local, ?LOGMODULE}, ?MODULE, log_level). - -%%%---------------------------------------------------------------------- -%%% Callback functions from gen_event -%%%---------------------------------------------------------------------- - -%%---------------------------------------------------------------------- -%% Func: init/1 -%% Returns: {ok, State} | -%% Other -%%---------------------------------------------------------------------- -init([File, Level]) -> - FileName = gen_full_log_filename(File, erlang:localtime()), - case file:open(FileName, [append, raw]) of - {ok, Fd} -> - erlang:send_after(?LOG_FILE_INTERVAL, self(), change_log_filename), - {ok, #state{fd = Fd, file = File, level = Level}}; - Error -> - Error - end. - -%%---------------------------------------------------------------------- -%% Func: handle_event/2 -%% Returns: {ok, State} | -%% {swap_handler, Args1, State1, Mod2, Args2} | -%% remove_handler -%%---------------------------------------------------------------------- -handle_event(Event, State) -> - write_event(State#state.fd, {erlang:localtime(), Event}), - {ok, State}. - -%%---------------------------------------------------------------------- -%% Func: handle_call/2 -%% Returns: {ok, Reply, State} | -%% {swap_handler, Reply, Args1, State1, Mod2, Args2} | -%% {remove_handler, Reply} -%%---------------------------------------------------------------------- -handle_call(log_level, State) -> - {ok, State#state.level, State}; -handle_call(_Request, State) -> - Reply = ok, - {ok, Reply, State}. - -%%---------------------------------------------------------------------- -%% Func: handle_info/2 -%% Returns: {ok, State} | -%% {swap_handler, Args1, State1, Mod2, Args2} | -%% remove_handler -%%---------------------------------------------------------------------- -handle_info({'EXIT', _Fd, _Reason}, _State) -> - remove_handler; -handle_info({emulator, _GL, reopen}, State) -> - file:close(State#state.fd), - rotate_log(State#state.file), - case file:open(State#state.file, [append, raw]) of - {ok, Fd} -> - {ok, State#state{fd = Fd}}; - Error -> - Error - end; -handle_info({emulator, GL, Chars}, State) -> - write_event(State#state.fd, {erlang:localtime(), {emulator, GL, Chars}}), - {ok, State}; - -handle_info(change_log_filename, State) -> - file:close(State#state.fd), - FileName = gen_full_log_filename(State#state.file, erlang:localtime()), - NewState = case file:open(FileName, [append, raw]) of - {ok, Fd} -> - State#state{fd = Fd}; - Error -> - ?TRACE("open ~s fail, reason:~p~n", [FileName, Error]), - State - end, - erlang:send_after(?LOG_FILE_INTERVAL, self(), change_log_filename), - {ok, NewState}; - -handle_info(_Info, State) -> - {ok, State}. - -%%---------------------------------------------------------------------- -%% Func: terminate/2 -%% Purpose: Shutdown the server -%% Returns: any -%%---------------------------------------------------------------------- -terminate(_Reason, _State) -> - ok. - -code_change(_OldVsn, State, _Extra) -> - {ok, State}. - -reopen_log() -> - ?LOGMODULE ! {emulator, noproc, reopen}. - -%%%---------------------------------------------------------------------- -%%% Internal functions -%%%---------------------------------------------------------------------- - -% Copied from erlang_logger_file_h.erl -write_event(Fd, {Time, {error, _GL, {Pid, Format, Args}}}) -> - T = write_time(Time), - case catch io_lib:format(add_node(Format, Pid), Args) of - S when is_list(S) -> - file:write(Fd, io_lib:format(T ++ S, [])); - _ -> - F = add_node("ERROR: ~p - ~p~n", Pid), - file:write(Fd, io_lib:format(T ++ F, [Format, Args])) - end; -write_event(Fd, {Time, {emulator, _GL, Chars}}) -> - T = write_time(Time), - case catch io_lib:format(Chars, []) of - S when is_list(S) -> - file:write(Fd, io_lib:format(T ++ S, [])); - _ -> - file:write(Fd, io_lib:format(T ++ "ERROR: ~p ~n", [Chars])) - end; -write_event(Fd, {Time, {info, _GL, {Pid, Info, _}}}) -> - T = write_time(Time), - file:write(Fd, io_lib:format(T ++ add_node("~p~n", Pid), [Info])); -write_event(Fd, {Time, {error_report, _GL, {Pid, std_error, Rep}}}) -> - T = write_time(Time), - S = format_report(Rep), - file:write(Fd, io_lib:format(T ++ S ++ add_node("", Pid), [])); -write_event(Fd, {Time, {info_report, _GL, {Pid, std_info, Rep}}}) -> - T = write_time(Time, "INFO REPORT"), - S = format_report(Rep), - file:write(Fd, io_lib:format(T ++ S ++ add_node("", Pid), [])); -write_event(Fd, {Time, {info_msg, _GL, {Pid, Format, Args}}}) -> - T = write_time(Time, "INFO REPORT"), - case catch io_lib:format(add_node(Format, Pid), Args) of - S when is_list(S) -> - file:write(Fd, io_lib:format(T ++ S, [])); - _ -> - F = add_node("ERROR: ~p - ~p~n", Pid), - file:write(Fd, io_lib:format(T ++ F, [Format, Args])) - end; -write_event(_, _) -> - ok. - -format_report(Rep) when is_list(Rep) -> - case string_p(Rep) of - true -> - io_lib:format("~s~n", [Rep]); - _ -> - format_rep(Rep) - end; -format_report(Rep) -> - io_lib:format("~p~n", [Rep]). - -format_rep([{Tag, Data} | Rep]) -> - io_lib:format(" ~p: ~p~n", [Tag, Data]) ++ format_rep(Rep); -format_rep([Other | Rep]) -> - io_lib:format(" ~p~n", [Other]) ++ format_rep(Rep); -format_rep(_) -> - []. - -add_node(X, Pid) when is_atom(X) -> - add_node(atom_to_list(X), Pid); -add_node(X, Pid) when node(Pid) /= node() -> - lists:concat([X, "** at node ", node(Pid), " **~n"]); -add_node(X, _) -> - X. - -string_p([]) -> - false; -string_p(Term) -> - string_p1(Term). - -string_p1([H | T]) when is_integer(H), H >= $\s, H < 255 -> - string_p1(T); -string_p1([$\n | T]) -> string_p1(T); -string_p1([$\r | T]) -> string_p1(T); -string_p1([$\t | T]) -> string_p1(T); -string_p1([$\v | T]) -> string_p1(T); -string_p1([$\b | T]) -> string_p1(T); -string_p1([$\f | T]) -> string_p1(T); -string_p1([$\e | T]) -> string_p1(T); -string_p1([H | T]) when is_list(H) -> - case string_p1(H) of - true -> string_p1(T); - _ -> false - end; -string_p1([]) -> true; -string_p1(_) -> false. - -write_time(Time) -> write_time(Time, "ERROR REPORT"). - -write_time({{Y, Mo, D}, {H, Mi, S}}, Type) -> - io_lib:format("~n=~s==== ~w-~.2.0w-~.2.0w ~.2.0w:~.2.0w:~.2.0w ===", - [Type, Y, Mo, D, H, Mi, S]). - -gen_full_log_filename(File, {{Y, Mo, D}, {H, Mi, S}}) -> - io_lib:format("~s_~w.~.2.0w.~.2.0w_~.2.0w-~.2.0w-~.2.0w", [File, Y, Mo, D, H, Mi, S]). - -%% @doc Rename the log file if exists, to "*-old.log". -%% This is needed in systems when the file must be closed before rotation (Windows). -%% On most Unix-like system, the file can be renamed from the command line and -%% the log can directly be reopened. -%% @spec (Filename::string()) -> ok -rotate_log(Filename) -> - case file:read_file_info(Filename) of - {ok, _FileInfo} -> - RotationName = filename:rootname(Filename), - file:rename(Filename, [RotationName, "-old.log"]), - ok; - {error, _Reason} -> - ok - end. diff --git a/src/srvNodeMgr/tools/gameWorld/test/misc/loglevel.erl b/src/srvNodeMgr/tools/gameWorld/test/misc/loglevel.erl deleted file mode 100644 index da3e28b..0000000 --- a/src/srvNodeMgr/tools/gameWorld/test/misc/loglevel.erl +++ /dev/null @@ -1,114 +0,0 @@ -%%%---------------------------------------------------------------------- -%%% File : loglevel.erl -%%% Created : 2010-08-30 -%%%---------------------------------------------------------------------- - --module(loglevel). - --export([set/1, get/0]). - --include("common.hrl"). --include("debug.hrl"). - -%% Error levels: --define(LOG_LEVELS, [{0, no_log, "No log"} - , {1, critical, "Critical"} - , {2, error, "Error"} - , {3, warning, "Warning"} - , {4, info, "Info"} - , {5, debug, "Debug"} - , {6, test, "Test"} -]). - -get() -> - Level = logger:get(), - case lists:keysearch(Level, 1, ?LOG_LEVELS) of - {value, Result} -> Result; - _ -> erlang:error({no_such_loglevel, Level}) - end. - -set(LogLevel) when is_atom(LogLevel) -> - set(level_to_integer(LogLevel)); -set(Loglevel) when is_integer(Loglevel) -> - try - io:format("$$$ loglevel:set, level is ~p~n", [Loglevel]), - {Mod, Code} = dynamic_compile:from_string(logger_src(Loglevel)), - code:load_binary(Mod, "logger_h.erl", Code) - catch - Type:Error -> ?CRITICAL_MSG("Error compiling logger (~p): ~p~n", [Type, Error]) - end; -set(_) -> - exit("Loglevel must be an integer"). - -level_to_integer(Level) -> - case lists:keysearch(Level, 2, ?LOG_LEVELS) of - {value, {Int, Level, _Desc}} -> Int; - _ -> erlang:error({no_such_loglevel, Level}) - end. - -%% -------------------------------------------------------------- -%% Code of the mcs logger, dynamically compiled and loaded -%% This allows to dynamically change log level while keeping a -%% very efficient code. -logger_src(Loglevel) -> - L = integer_to_list(Loglevel), - "-module(logger). - - -export([test_msg/4, - debug_msg/4, - info_msg/4, - warning_msg/4, - error_msg/4, - critical_msg/4, - get/0]). - - get() -> " ++ L ++ ". - - %% Helper functions - test_msg(Module, Line, Format, Args) when " ++ L ++ " >= 6 -> - notify(info_msg, - \"T(~p:~p:~p) : \"++Format++\"~n\", - [self(), Module, Line]++Args); - test_msg(_,_,_,_) -> ok. - - debug_msg(Module, Line, Format, Args) when " ++ L ++ " >= 5 -> - notify(info_msg, - \"D(~p:~p:~p) : \"++Format++\"~n\", - [self(), Module, Line]++Args); - debug_msg(_,_,_,_) -> ok. - - info_msg(Module, Line, Format, Args) when " ++ L ++ " >= 4 -> - notify(info_msg, - \"I(~p:~p:~p) : \"++Format++\"~n\", - [self(), Module, Line]++Args); - info_msg(_,_,_,_) -> ok. - - warning_msg(Module, Line, Format, Args) when " ++ L ++ " >= 3 -> - notify(error, - \"W(~p:~p:~p) : \"++Format++\"~n\", - [self(), Module, Line]++Args); - warning_msg(_,_,_,_) -> ok. - - error_msg(Module, Line, Format, Args) when " ++ L ++ " >= 2 -> - case Args of - %% start with : ** Node php - [42,42,32,78,111,100,101,32,112,104,112|_] -> - ok; - _ -> - notify(error, - \"E(~p:~p:~p) : \"++Format++\"~n\", - [self(), Module, Line]++Args) - end; - error_msg(_,_,_,_) -> ok. - - critical_msg(Module, Line, Format, Args) when " ++ L ++ " >= 1 -> - notify(error, - \"C(~p:~p:~p) : \"++Format++\"~n\", - [self(), Module, Line]++Args); - critical_msg(_,_,_,_) -> ok. - - %% Distribute the message to the Erlang error logger - notify(Type, Format, Args) -> - LoggerMsg = {Type, group_leader(), {self(), Format, Args}}, - gen_event:notify(logger_mgr, LoggerMsg). - ". \ No newline at end of file diff --git a/src/srvNodeMgr/tools/gameWorld/test/misc/misc.erl b/src/srvNodeMgr/tools/gameWorld/test/misc/misc.erl index 3137046..c0ed46c 100644 --- a/src/srvNodeMgr/tools/gameWorld/test/misc/misc.erl +++ b/src/srvNodeMgr/tools/gameWorld/test/misc/misc.erl @@ -1,159 +1,5 @@ -%%%---------------------------------------- -%%% @Module : misc -%%% @Author : csj -%%% @Created : 2010.10.05 -%%% @Description: 常用函数 -%%%---------------------------------------- - -module(misc). -%% -%% Include files -%% --include("common.hrl"). --include("record.hrl"). --include("goods.hrl"). -%% -%% Exported Functions -%% - --compile(export_all). - - -%% -%% API Functions -%% -%% get the pid of a registered name -whereis_name({local, Atom}) -> - erlang:whereis(Atom); - -whereis_name({global, Atom}) -> - global:whereis_name(Atom). - -register(local, Name, Pid) -> - erlang:register(Name, Pid); - -register(global, Name, Pid) -> -%% case global:whereis_name(Name) of -%% Pid0 when is_pid(Pid0) -> -%% exit(Pid0,normal); -%% undefined -> -%% global:re_register_name(Name, Pid) -%% end. - global:re_register_name(Name, Pid); - -register(unique, Name, Pid) -> - global:register_name(Name, Pid). - -unregister({local, Atom}) -> - erlang:unregister(Atom); - -unregister({global, Atom}) -> - global:unregister(Atom). - -is_process_alive(Pid) -> - try - if is_pid(Pid) -> - %%现在都是单节点,无需访问节点来判断 -%% case rpc:call(node(Pid), erlang, is_process_alive, [Pid]) of -%% {badrpc, _Reason} -> false; -%% Res -> Res -%% end; - erlang:is_process_alive(Pid); - true -> false - end - catch - _:_ -> false - end. - -%% time format -one_to_two(One) -> io_lib:format("~2..0B", [One]). - -%% @doc get the time's seconds for integer type -%% @spec get_seconds(Time) -> integer() -get_seconds(Time) -> - {_MegaSecs, Secs, _MicroSecs} = Time, - Secs. - -time_format(Now) -> - {{Y, M, D}, {H, MM, S}} = calendar:now_to_local_time(Now), - lists:concat([Y, "-", one_to_two(M), "-", one_to_two(D), " ", - one_to_two(H), ":", one_to_two(MM), ":", one_to_two(S)]). -date_format(Now) -> - {{Y, M, D}, {_H, _MM, _S}} = calendar:now_to_local_time(Now), - lists:concat([Y, "-", one_to_two(M), "-", one_to_two(D)]). -date_hour_format(Now) -> - {{Y, M, D}, {H, _MM, _S}} = calendar:now_to_local_time(Now), - lists:concat([Y, "-", one_to_two(M), "-", one_to_two(D), " ", one_to_two(H)]). -date_hour_minute_format(Now) -> - {{Y, M, D}, {H, MM, _S}} = calendar:now_to_local_time(Now), - lists:concat([Y, "-", one_to_two(M), "-", one_to_two(D), " ", one_to_two(H), "-", one_to_two(MM)]). -%% split by - -minute_second_format(Now) -> - {{_Y, _M, _D}, {H, MM, _S}} = calendar:now_to_local_time(Now), - lists:concat([one_to_two(H), "-", one_to_two(MM)]). - -hour_minute_second_format(Now) -> - {{_Y, _M, _D}, {H, MM, S}} = calendar:now_to_local_time(Now), - lists:concat([one_to_two(H), ":", one_to_two(MM), ":", one_to_two(S)]). - -rand_to_process(S) -> - Rand = random:uniform(?SEND_MSG), - lists:nth(Rand, S). - - -%% 这里先修改成原子,如果原子不够用,在改回list然后注册成全局的 -player_process_name(PlayerId) when is_integer(PlayerId) or is_atom(PlayerId) -> - tool:to_atom(lists:concat([p_p_, PlayerId])); -player_process_name(PlayerId) when is_list(PlayerId) -> - tool:to_atom(lists:flatten(["p_p_" | PlayerId])); -player_process_name(PlayerId) when is_binary(PlayerId) -> - tool:to_atom(lists:concat([p_p_, tool:md5(PlayerId)])). - -%% 在一账号多个角色的情况下,需要按账号ID判断唯一性 -player_process_accountname(AccountId) when is_integer(AccountId) or is_atom(AccountId) -> - lists:concat([p_a_, AccountId]); -player_process_accountname(AccountId) when is_list(AccountId) -> - lists:flatten(["p_a_" | AccountId]); -player_process_accountname(AccountId) when is_binary(AccountId) -> - lists:concat([p_a_, tool:md5(AccountId)]). - -%% 创建进程名 -create_process_name(Prefix, List) -> - tool:to_atom(lists:concat(lists:flatten([Prefix] ++ lists:map(fun(T) -> ['_', T] end, List)))). - -%% 原子拼装 -create_atom(Prefix, List) -> - tool:to_atom(lists:concat(lists:flatten([Prefix] ++ lists:map(fun(T) -> ['_', T] end, List)))). - -%% 获取来源IP -get_ip(Socket) -> - case inet:peername(Socket) of - {ok, {PeerIP, _Port}} -> - ip_to_binary(PeerIP); - {error, _NetErr} -> - "" - end. - -ip_to_binary(Ip) -> - case Ip of - {A1, A2, A3, A4} -> - [integer_to_list(A1), ".", integer_to_list(A2), ".", integer_to_list(A3), ".", integer_to_list(A4)]; - _ -> - "-" - end. - -ip_list_to_binary(Data) -> - case Data of - [] -> ""; - undefined -> "-"; - {IP, _PORT} -> ip_to_binary(IP); - _ when is_list(Data) -> - [H | T] = Data, - [ip_list_to_binary(H), ",", ip_list_to_binary(T)]; - _ -> "-" - end. - get_child_count(Atom) -> case whereis_name({local, Atom}) of undefined -> @@ -178,25 +24,6 @@ get_child_message_queue_length(Atom) -> Child_list) end. -%% desc: 创建玩家的物品ets表编号 -create_goods_ets_name(Num) -> - case lists:member(Num, lists:seq(1, ?MAX_GOODS_ETS_NUM)) of - true -> tool:to_atom(lists:concat([ets_goods_online_, Num])); - false -> none - end. -%% desc: 创建玩家的物品ets表编号 -create_goods_attr_ets_name(Num) -> - case lists:member(Num, lists:seq(1, ?MAX_GOODS_ETS_NUM)) of - true -> tool:to_atom(lists:concat([ets_goods_attribute_, Num])); - false -> none - end. -%% desc: 创建玩家的物品ets表编号 -create_goods_polish_ets_name(Num) -> - case lists:member(Num, lists:seq(1, ?MAX_GOODS_ETS_NUM)) of - true -> tool:to_atom(lists:concat([ets_polish_, Num])); - false -> none - end. - %% -------------------------------------------------------------------- %% Func: get pid info/7 %% Param Process: atom Pid or Pid RegName @@ -542,21 +369,5 @@ get_http_content(Url) -> "" end. -cancel_timer(Timer) -> - case get(Timer) of - undefined -> skip; - Timer1 -> - erlang:cancel_timer(Timer1) - end. - -write_system_info(Pid, Module, Args) -> - ets:insert(?ETS_SYSTEM_INFO, {Pid, Module, Args}). - -delete_system_info(Pid) -> - ets:delete(?ETS_SYSTEM_INFO, Pid). -write_monitor_pid(Pid, Module, Args) -> - ets:insert(?ETS_MONITOR_PID, {Pid, Module, Args}). -delete_monitor_pid(Pid) -> - ets:delete(?ETS_MONITOR_PID, Pid). diff --git a/src/uuidMd5/utMd5.erl b/src/uuidMd5/utMd5.erl index 865ea3a..84a3619 100644 --- a/src/uuidMd5/utMd5.erl +++ b/src/uuidMd5/utMd5.erl @@ -16,7 +16,7 @@ getMd5HexBin(Str) -> -spec(md5BinToHex(Md5Bin :: binary()) -> string()). md5BinToHex(Md5Bin) -> - utHex:binaryToHex(Md5Bin). + utHex:binaryToHex(Md5Bin).:q! -spec(md5BinToHexBin(Md5Bin :: binary()) -> binary()). md5BinToHexBin(Md5Bin) ->