Skip to content

Commit e102ce5

Browse files
NewFutureCopilot
andauthored
fix(docker): prevent zombie process accumulation (#711)
* fix(docker): prevent zombie process accumulation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * fix(docker): forward signals to startup processes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: NewFuture <6290356+NewFuture@users.noreply.github.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 0a80f32 commit e102ce5

5 files changed

Lines changed: 302 additions & 11 deletions

File tree

‎.github/workflows/build.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,9 @@ jobs:
418418
docker run --platform $platform --rm -v "$(pwd):/ddns/" ${{ env.DOCKER_IMG }}:$tag -c /ddns/tests/config/debug.json -c /ddns/tests/config/noip.json
419419
docker run --platform $platform --rm -v "$(pwd):/ddns/" ${{ env.DOCKER_IMG }}:$tag -c https://ddns.newfuture.cc/tests/config/debug.json
420420
docker run --platform $platform --rm -v "$(pwd):/ddns/" ${{ env.DOCKER_IMG }}:$tag -c /ddns/tests/config/he-proxies.json
421+
if [ "$platform" = "linux/amd64" ]; then
422+
sh tests/scripts/test-docker-zombies.sh "${{ env.DOCKER_IMG }}:$tag" "$platform"
423+
fi
421424
done
422425
423426
# 上传测试结果和镜像

‎ddns/ip.py‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
#!/usr/bin/env python
22
# -*- coding:utf-8 -*-
33
from re import compile
4-
from os import name as os_name, popen
4+
from os import name as os_name
55
from socket import socket, getaddrinfo, gethostname, AF_INET, AF_INET6, SOCK_DGRAM
66
from logging import debug, error
77

88
from .util.http import request
9+
from .util.try_run import try_run
910

1011
# 模块级别的SSL验证配置,默认使用auto模式
1112
ssl_verify = "auto"
@@ -113,16 +114,23 @@ def public_v6(url=None, reg=IPV6_REG): # 公网IPV6地址
113114
return _try_multiple_apis(PUBLIC_IPV6_APIS, reg, "IPv6")
114115

115116

117+
def _read_network_config():
118+
# type: () -> str | None
119+
if os_name == "nt":
120+
return try_run(["ipconfig"])
121+
122+
output = try_run(["ip", "address"])
123+
if output is None:
124+
output = try_run(["ifconfig"])
125+
return output
126+
127+
116128
def _ip_regex_match(parrent_regex, match_regex):
117129
ip_pattern = compile(parrent_regex)
118130
matcher = compile(match_regex)
119131

120-
if os_name == "nt": # windows:
121-
cmd = "ipconfig"
122-
else:
123-
cmd = "ip address || ifconfig 2>/dev/null"
124-
125-
for s in popen(cmd).readlines():
132+
output = _read_network_config()
133+
for s in (output or "").splitlines(True):
126134
addr = ip_pattern.search(s)
127135
if addr and matcher.match(addr.group(1)):
128136
return addr.group(1)

‎docker/Dockerfile‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ RUN mkdir /output && cp dist/ddns /output/
5454
COPY docker/entrypoint.sh /output/
5555

5656
FROM alpine:${HOST_VERSION}
57+
RUN apk add --no-cache tini
5758
COPY --from=builder /output/* /bin/
5859
WORKDIR /ddns
59-
ENTRYPOINT [ "/bin/entrypoint.sh" ]
60+
ENTRYPOINT [ "/sbin/tini", "-g", "--", "/bin/entrypoint.sh" ]
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
#!/bin/sh
2+
# Verify that regex IP detection neither launches an intermediate shell nor
3+
# leaves zombie processes when crond is the container's PID 1.
4+
5+
set -eu
6+
7+
if [ "${DDNS_SIGNAL_TEST_IP:-}" = "1" ]; then
8+
trap ': > /signal/terminated; exit 0' TERM INT
9+
: > /signal/started
10+
while :; do
11+
sleep 1
12+
done
13+
fi
14+
15+
TEST_ROOT=/tmp/ddns-zombie-test
16+
TEST_BIN="$TEST_ROOT/bin"
17+
PARENT_LOG="$TEST_ROOT/ip-parents"
18+
READY_FILE="$TEST_ROOT/ready"
19+
20+
setup_container() {
21+
mkdir -p "$TEST_BIN"
22+
cat > "$TEST_BIN/ip" <<'EOF'
23+
#!/bin/sh
24+
set -eu
25+
26+
if [ "$#" -ne 1 ] || [ "$1" != "address" ]; then
27+
echo "Unexpected ip arguments: $*" >&2
28+
exit 64
29+
fi
30+
31+
cat "/proc/$PPID/comm" >> /tmp/ddns-zombie-test/ip-parents
32+
cat <<'EOF_IP_OUTPUT'
33+
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500
34+
inet6 2001:db8::42/64 scope global
35+
EOF_IP_OUTPUT
36+
EOF
37+
chmod 755 "$TEST_BIN/ip"
38+
: > "$PARENT_LOG"
39+
: > "$READY_FILE"
40+
}
41+
42+
check_process_tree() {
43+
init_name=$(cat /proc/1/comm)
44+
if [ "$init_name" != "tini" ]; then
45+
echo "Expected tini as PID 1, got $init_name" >&2
46+
return 1
47+
fi
48+
49+
crond_parent=$(ps -o pid,ppid,stat,comm | awk 'NR > 1 && $4 == "crond" { print $2; exit }')
50+
if [ "$crond_parent" != "1" ]; then
51+
echo "Expected crond to be a direct child of tini, got PPID ${crond_parent:-missing}" >&2
52+
return 1
53+
fi
54+
}
55+
56+
check_container() {
57+
expected_runs=$1
58+
actual_runs=$(wc -l < "$PARENT_LOG")
59+
60+
check_process_tree
61+
62+
if [ "$actual_runs" -ne "$expected_runs" ]; then
63+
echo "Expected $expected_runs ip executions, got $actual_runs" >&2
64+
cat "$PARENT_LOG" >&2
65+
exit 1
66+
fi
67+
68+
if grep -Eq "^(sh|ash|busybox)$" "$PARENT_LOG"; then
69+
echo "Regex IP detection launched ip through an intermediate shell" >&2
70+
cat "$PARENT_LOG" >&2
71+
exit 1
72+
fi
73+
74+
zombies=$(ps -o pid,ppid,stat,comm | awk 'NR > 1 && $3 ~ /^Z/ { print }')
75+
if [ -n "$zombies" ]; then
76+
echo "Zombie processes found after regex IP detection:" >&2
77+
echo "$zombies" >&2
78+
exit 1
79+
fi
80+
81+
echo "Regex IP detection completed $actual_runs runs without shell intermediates or zombies"
82+
}
83+
84+
test_startup_signal_forwarding() {
85+
docker run --detach \
86+
--name "$signal_container" \
87+
--platform "$platform" \
88+
--env "PATH=/tmp:$base_path" \
89+
--env DDNS_DNS=debug \
90+
--env DDNS_IPV6=zombie-test.example \
91+
--env 'DDNS_INDEX6=regex:2001:db8:.*' \
92+
--env DDNS_CACHE=false \
93+
--env DDNS_SIGNAL_TEST_IP=1 \
94+
--volume "$script_path:/tmp/ip:ro" \
95+
--volume "$signal_dir:/signal" \
96+
"$image" >/dev/null
97+
98+
attempt=0
99+
until [ -f "$signal_dir/started" ]; do
100+
attempt=$((attempt + 1))
101+
if [ "$attempt" -ge 30 ]; then
102+
echo "Timed out waiting for the initial DDNS update" >&2
103+
docker logs "$signal_container" >&2
104+
exit 1
105+
fi
106+
sleep 1
107+
done
108+
109+
docker stop --time 5 "$signal_container" >/dev/null
110+
if [ ! -f "$signal_dir/terminated" ]; then
111+
echo "Tini did not forward SIGTERM to the initial DDNS process group" >&2
112+
exit 1
113+
fi
114+
115+
exit_code=$(docker inspect --format '{{.State.ExitCode}}' "$signal_container")
116+
if [ "$exit_code" -eq 137 ]; then
117+
echo "Initial DDNS shutdown required SIGKILL" >&2
118+
exit 1
119+
fi
120+
echo "Tini forwarded SIGTERM during the initial DDNS update"
121+
}
122+
123+
case "${1:-}" in
124+
--setup)
125+
setup_container
126+
exit 0
127+
;;
128+
--check)
129+
check_container "$2"
130+
exit 0
131+
;;
132+
--ready)
133+
test -f "$READY_FILE"
134+
check_process_tree
135+
exit 0
136+
;;
137+
esac
138+
139+
image=${1:?Usage: test-docker-zombies.sh IMAGE [PLATFORM]}
140+
platform=${2:-linux/amd64}
141+
runs=${DDNS_ZOMBIE_TEST_RUNS:-8}
142+
script_dir=$(cd "$(dirname "$0")" && pwd)
143+
script_path="$script_dir/$(basename "$0")"
144+
container="ddns-zombie-test-$$"
145+
signal_container="${container}-signal"
146+
signal_dir="${TMPDIR:-/tmp}/${signal_container}"
147+
base_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
148+
mkdir -p "$signal_dir"
149+
150+
cleanup() {
151+
docker rm -f "$container" >/dev/null 2>&1 || true
152+
docker rm -f "$signal_container" >/dev/null 2>&1 || true
153+
rm -rf "$signal_dir"
154+
}
155+
trap cleanup 0 1 2 15
156+
157+
expected_entrypoint='["/sbin/tini","-g","--","/bin/entrypoint.sh"]'
158+
actual_entrypoint=$(docker image inspect --format '{{json .Config.Entrypoint}}' "$image")
159+
if [ "$actual_entrypoint" != "$expected_entrypoint" ]; then
160+
echo "Unexpected image entrypoint: $actual_entrypoint" >&2
161+
exit 1
162+
fi
163+
164+
docker run --detach \
165+
--name "$container" \
166+
--platform "$platform" \
167+
--entrypoint /sbin/tini \
168+
--volume "$script_dir:/tests:ro" \
169+
"$image" \
170+
-g -- /bin/sh -c "/bin/sh /tests/test-docker-zombies.sh --setup; exec crond -f" >/dev/null
171+
172+
attempt=0
173+
until docker exec "$container" /bin/sh /tests/test-docker-zombies.sh --ready 2>/dev/null; do
174+
attempt=$((attempt + 1))
175+
if [ "$attempt" -ge 30 ]; then
176+
echo "Timed out waiting for the zombie test container" >&2
177+
docker logs "$container" >&2
178+
exit 1
179+
fi
180+
sleep 1
181+
done
182+
183+
test_path="$TEST_BIN:$base_path"
184+
run=0
185+
while [ "$run" -lt "$runs" ]; do
186+
output=$(docker exec --env "PATH=$test_path" "$container" \
187+
/bin/ddns \
188+
--dns=debug \
189+
'--index6=regex:2001:db8:.*' \
190+
--ipv6=zombie-test.example \
191+
--cache=false)
192+
if ! printf '%s\n' "$output" | grep -q '^\[IPv6\] 2001:db8::42$'; then
193+
echo "Regex IPv6 result did not reach the debug provider:" >&2
194+
echo "$output" >&2
195+
exit 1
196+
fi
197+
run=$((run + 1))
198+
done
199+
200+
sleep 1
201+
docker exec "$container" /bin/sh /tests/test-docker-zombies.sh --check "$runs"
202+
203+
docker stop --time 5 "$container" >/dev/null
204+
exit_code=$(docker inspect --format '{{.State.ExitCode}}' "$container")
205+
if [ "$exit_code" -eq 137 ]; then
206+
echo "Container required SIGKILL instead of a graceful Tini shutdown" >&2
207+
exit 1
208+
fi
209+
echo "Tini forwarded shutdown with container exit code $exit_code"
210+
211+
test_startup_signal_forwarding

‎tests/test_ip.py‎

Lines changed: 71 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -258,11 +258,79 @@ def mock_request_side_effect(method, url, **kwargs):
258258
self.assertEqual(result, "1.2.3.4")
259259
self.assertEqual(mock_request.call_count, len(ip.PUBLIC_IPV4_APIS) + 1)
260260

261+
@patch("ddns.ip.os_name", "posix")
262+
@patch("ddns.ip.try_run")
263+
def test_regex_v4_uses_ip_address(self, mock_try_run):
264+
"""测试Unix IPv4正则通过参数列表执行ip命令"""
265+
mock_try_run.return_value = "2: eth0\n inet 192.0.2.10/24 scope global eth0\n"
266+
267+
result = ip.regex_v4(r"192\.0\.2\..*")
268+
269+
self.assertEqual(result, "192.0.2.10")
270+
mock_try_run.assert_called_once_with(["ip", "address"])
271+
272+
@patch("ddns.ip.os_name", "posix")
273+
@patch("ddns.ip.try_run")
274+
def test_regex_v6_uses_ip_address(self, mock_try_run):
275+
"""测试Unix IPv6正则通过参数列表执行ip命令"""
276+
mock_try_run.return_value = "2: eth0\n inet6 2409:8a00::1/64 scope global\n"
277+
278+
result = ip.regex_v6(r"2409:.*")
279+
280+
self.assertEqual(result, "2409:8a00::1")
281+
mock_try_run.assert_called_once_with(["ip", "address"])
282+
283+
@patch("ddns.ip.os_name", "posix")
284+
@patch("ddns.ip.try_run")
285+
def test_regex_falls_back_to_ifconfig_when_ip_fails(self, mock_try_run):
286+
"""测试ip命令失败时直接执行ifconfig"""
287+
mock_try_run.side_effect = [None, "inet addr:198.51.100.7 Mask:255.255.255.0\n"]
288+
289+
result = ip.regex_v4(r"198\.51\.100\..*")
290+
291+
self.assertEqual(result, "198.51.100.7")
292+
self.assertEqual(mock_try_run.call_args_list[0][0][0], ["ip", "address"])
293+
self.assertEqual(mock_try_run.call_args_list[1][0][0], ["ifconfig"])
294+
295+
@patch("ddns.ip.os_name", "posix")
296+
@patch("ddns.ip.try_run")
297+
def test_regex_does_not_fallback_after_successful_ip_command(self, mock_try_run):
298+
"""测试ip命令成功但不匹配时不执行ifconfig"""
299+
mock_try_run.return_value = "2: eth0\n inet 192.0.2.10/24 scope global eth0\n"
300+
301+
result = ip.regex_v4(r"172\.16\..*")
302+
303+
self.assertIsNone(result)
304+
mock_try_run.assert_called_once_with(["ip", "address"])
305+
306+
@patch("ddns.ip.os_name", "posix")
307+
@patch("ddns.ip.try_run")
308+
def test_regex_returns_none_when_network_commands_fail(self, mock_try_run):
309+
"""测试ip和ifconfig均失败时返回空结果"""
310+
mock_try_run.side_effect = [None, None]
311+
312+
result = ip.regex_v4(r".*")
313+
314+
self.assertIsNone(result)
315+
self.assertEqual(mock_try_run.call_count, 2)
316+
317+
@patch("ddns.ip.os_name", "nt")
318+
@patch("ddns.ip.try_run")
319+
def test_regex_v4_uses_ipconfig_on_windows(self, mock_try_run):
320+
"""测试Windows IPv4正则直接执行ipconfig"""
321+
mock_try_run.return_value = "IPv4 Address. . . . . . . . . . . : 203.0.113.9\r\n"
322+
323+
result = ip.regex_v4(r"203\.0\.113\..*")
324+
325+
self.assertEqual(result, "203.0.113.9")
326+
mock_try_run.assert_called_once_with(["ipconfig"])
327+
261328
@patch("ddns.ip.public_v4")
262-
@patch("ddns.ip.popen")
263-
def test_get_ip_regex_rule_fallback(self, mock_popen, mock_public_v4):
329+
@patch("ddns.ip.os_name", "posix")
330+
@patch("ddns.ip.try_run")
331+
def test_get_ip_regex_rule_fallback(self, mock_try_run, mock_public_v4):
264332
"""测试regex规则返回空结果时继续回退"""
265-
mock_popen.return_value.readlines.return_value = ["inet 192.168.1.10/24", "inet 10.0.0.2/24"]
333+
mock_try_run.return_value = "inet 192.168.1.10/24\ninet 10.0.0.2/24\n"
266334
mock_public_v4.return_value = "1.2.3.4"
267335

268336
result = get_ip("4", ["regex:172\\.16\\..*", "public"])

0 commit comments

Comments
 (0)