update handle_terminate

4.0
vapao 2023-03-29 15:37:56 +08:00
parent 5af083c118
commit f31f01ef06
1 changed files with 27 additions and 10 deletions

View File

@ -121,25 +121,42 @@ class TaskView(View):
return json_response(error=error) return json_response(error=error)
KILLER = '''
function kill_tree {
local pid=$1
local and_self=${2:-0}
local children=$(pgrep -P $pid)
for child in $children; do
kill_tree $child 1
done
if [ $and_self -eq 1 ]; then
kill $pid
fi
}
kill_tree %s
'''
@auth('exec.task.do|deploy.request.do') @auth('exec.task.do|deploy.request.do')
def handle_terminate(request): def handle_terminate(request):
form, error = JsonParser( form, error = JsonParser(
Argument('token', help='参数错误'), Argument('token', help='参数错误')
Argument('target', help='参数错误')
).parse(request.body) ).parse(request.body)
if error is None: if error is None:
rds = get_redis_connection() rds = get_redis_connection()
rds_key = f'PID:{form.token}:{form.target}' pid_str = rds.get(form.token)
pid = rds.get(rds_key) if not pid_str:
if not pid:
return json_response(error='未找到关联进程') return json_response(error='未找到关联进程')
if form.target.isdigit(): target, pid = pid_str.decode().split('.')
host = Host.objects.get(pk=form.target) if target.isdigit():
host = Host.objects.get(pk=target)
with host.get_ssh() as ssh: with host.get_ssh() as ssh:
ssh.exec_command_raw(f'kill -9 {pid.decode()}') command = KILLER % pid
elif form.target == 'local': ssh.exec_command_raw(command)
elif target == 'local':
gid = os.getpgid(int(pid)) gid = os.getpgid(int(pid))
if gid: if gid:
os.killpg(gid, 9) os.killpg(gid, 9)
rds.delete(rds_key) rds.delete(form.token)
return json_response(error=error) return json_response(error=error)