-
Notifications
You must be signed in to change notification settings - Fork 0
/
console.lua
101 lines (79 loc) · 2.31 KB
/
console.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
local cf = require "cf"
local tcp = require "internal.TCP"
local server
local USAGE = [[
Welcome! This is cfadmin Debug Console:
gc - Can run/stop/modify/count garbage collectors.
run - Execute the lua script like `main` coroutine.
dump - Prints more information about the specified data structure.
stat - Process usage data analysis report.
flush - flush all internal cache.
>>> ]]
local function import(pkg)
return assert(package.searchers[2](pkg))()
end
local command = {}
-- GC 命令处理
command['gc'] = import "debug.gc"
-- RUN 命令处理
command['run'] = import "debug.run"
-- DUMP 命令处理
command['dump'] = import "debug.dump"
-- STAT 命令处理
command['stat'] = import "debug.stat"
-- FlUSH 命令处理
command['flush'] = import "debug.flush"
-- 解析客户端请求
local function command_split(cmd)
local cmds = {}
string.gsub(cmd, "[^ \t\r\n]+", function (s)
cmds[#cmds+1] = s
end)
return table.remove(cmds, 1), cmds
end
-- 客户端处理事件
local function dispatch(fd)
local client = tcp:new():set_fd(fd)
client:send(USAGE)
while true do
local cmd = client:readline("[\r]?\n", true)
if not cmd then
break
end
local args
cmd, args = command_split(cmd)
if cmd then
cmd = cmd:lower()
end
local f = command[cmd]
if f then
client:send(f(table.unpack(args)))
client:send("\r\n>>> ")
else
client:send(USAGE)
end
end
return client:close()
end
local debug = {}
---comment 启动`IP`与`Port`服务
---@param ip string @监听地址
---@param port integer @监听端口
function debug.start(ip, port)
assert(not worker, "[Lua Debug Console Error]: Only available in single process mode.")
server = assert(not server, "[Lua Debug Console Error]: Attempted to start multiple debug console.")
return cf.fork(function ()
server = tcp:new()
assert(server:listen(ip, port, dispatch))
end)
end
---comment 启动`Unix Domain Socket`监听服务
---@param unix_domain_path string @启动环境
function debug.startx(unix_domain_path)
server = assert(not server, "[Lua Debug Console Error]: Attempted to start multiple debug console.")
return cf.fork(function ()
server = tcp:new()
assert(server:listen_ex(unix_domain_path, true, dispatch))
end)
end
return debug