-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.sh
More file actions
executable file
·360 lines (316 loc) · 10.7 KB
/
Copy pathserver.sh
File metadata and controls
executable file
·360 lines (316 loc) · 10.7 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
#!/usr/bin/env bash
# ============================================================
# Resume Tailor — Server Management Script
# ============================================================
# Clean start / stop / status / restart for the Gradio server.
#
# The listening port is the source of truth (not PID files alone).
# The script always verifies that a process is actually running.
#
# Usage:
# ./server.sh start Start the server in the background
# ./server.sh stop Stop the server (SIGTERM, then SIGKILL)
# ./server.sh status Show whether the server is running
# ./server.sh restart Stop, then start again
# ============================================================
set -euo pipefail
# Absolute project root — works no matter which directory this is run from.
PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Port the Gradio app listens on (overridable via GRADIO_SERVER_PORT).
PORT="${GRADIO_SERVER_PORT:-7860}"
VENV_DIR="$PROJECT_DIR/venv"
VENV_PYTHON="$VENV_DIR/bin/python"
PIDFILE="$PROJECT_DIR/.server.pid"
LOG_FILE="$PROJECT_DIR/server.log"
# ------------------------------------------------------------
# Port helpers
# ------------------------------------------------------------
# Print the PID(s) of every process listening on $PORT.
port_pids() {
# Primary method: lsof (returns bare PIDs).
if command -v lsof >/dev/null 2>&1; then
lsof -ti tcp:"$PORT" 2>/dev/null || true
return 0
fi
# Fallback 1: fuser.
if command -v fuser >/dev/null 2>&1; then
fuser "$PORT/tcp" 2>/dev/null | tr -s ' ' '\n' | grep -E '^[0-9]+$' || true
return 0
fi
# Fallback 2: parse /proc (usable even without lsof/fuser/ss).
if [ -x "$VENV_PYTHON" ]; then
"$VENV_PYTHON" - "$PORT" <<'PY' 2>/dev/null || true
import os
import socket
import sys
def main():
try:
port = int(sys.argv[1])
except (ValueError, IndexError):
return
# Nothing is listening on the port -> report nothing.
s = socket.socket()
s.settimeout(1)
try:
s.connect(("127.0.0.1", port))
s.close()
except OSError:
return
hex_port = format(port, "04X")
inodes = set()
for path in ("/proc/net/tcp", "/proc/net/tcp6"):
try:
with open(path) as f:
lines = f.read().splitlines()[1:]
except OSError:
continue
for line in lines:
fields = line.split()
if len(fields) < 10 or fields[3] != "0A": # 0A = TCP_LISTEN
continue
local_port = fields[1].rsplit(":", 1)[-1]
if local_port.upper() != hex_port:
continue
inodes.add(fields[9])
if not inodes:
return
# Map socket inode -> PID by scanning /proc/<pid>/fd.
seen = set()
for pid_dir in os.listdir("/proc"):
if not pid_dir.isdigit():
continue
fd_dir = "/proc/%s/fd" % pid_dir
try:
fds = os.listdir(fd_dir)
except OSError:
continue
try:
for fd in fds:
target = os.readlink(os.path.join(fd_dir, fd))
if target.startswith("socket:[") and target[8:-1] in inodes:
pid = int(pid_dir)
if pid not in seen:
seen.add(pid)
print(pid)
except OSError:
continue
main()
PY
return 0
fi
return 0
}
# True (exit 0) if a process is actually listening on $PORT.
is_server_running() {
local pids
pids="$(port_pids | sort -u 2>/dev/null || true)"
[ -n "$pids" ]
}
# True (exit 0) if the kernel has a LISTEN socket bound to $PORT, even when no
# live process owns it. Such an "orphaned" listener can be left behind by a
# server that was hard-killed; lsof/ss/fuser only report sockets owned by a
# running process, so they miss it — yet it still blocks the port from being
# bound. Reading /proc/net/tcp directly catches it.
kernel_has_listener() {
local hex_port
hex_port="$(printf '%04X' "$PORT")"
awk -v hp="$hex_port" '
NR > 1 {
if ($4 != "0A") next # 0A = TCP_LISTEN
split($2, a, ":")
if (toupper(a[2]) == hp) { found = 1; exit }
}
END { exit found ? 0 : 1 }
' "/proc/net/tcp" "/proc/net/tcp6" 2>/dev/null
}
# Print a human-readable explanation of the orphaned-listener state.
orphaned_listener_hint() {
echo "Port $PORT is bound by a LISTEN socket that no running process owns" >&2
echo " (an orphaned/stale listener left over from a killed server)." >&2
echo " It is invisible to lsof/ss, so it cannot be killed normally. Options:" >&2
echo " - Run on another port: GRADIO_SERVER_PORT=$((PORT + 1)) $0 start" >&2
echo " - Force-close it (root): sudo ss -K listen $PORT" >&2
echo " - Reboot to clear it." >&2
}
# ------------------------------------------------------------
# IP address (for display messages)
# ------------------------------------------------------------
get_ip_address() {
local ip=""
if command -v hostname >/dev/null 2>&1; then
ip="$(hostname -I 2>/dev/null | awk '{print $1}')"
fi
case "$ip" in
""|"127.0.0.1"|"::1")
if [ -x "$VENV_PYTHON" ]; then
ip="$("$VENV_PYTHON" - <<'PY' 2>/dev/null || true
import socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0], end="")
s.close()
except Exception:
print("127.0.0.1", end="")
PY
)"
fi
;;
esac
[ -n "$ip" ] || ip="127.0.0.1"
echo "$ip"
}
# ------------------------------------------------------------
# start
# ------------------------------------------------------------
start_server() {
if is_server_running; then
local existing
existing="$(port_pids | sort -u 2>/dev/null | head -n 1)"
echo "Server already running on port $PORT (PID: $existing)"
exit 1
fi
# A port bound by an orphaned listener is not "running", but it still blocks
# the port. Detect it before launching so the failure is explained instead
# of surfacing as Gradio's cryptic "Cannot find empty port" traceback.
if kernel_has_listener; then
orphaned_listener_hint
exit 1
fi
if [ ! -x "$VENV_PYTHON" ]; then
echo "Virtual environment not found: $VENV_DIR/bin/python" >&2
exit 1
fi
# Activate the virtual environment.
set +u
# shellcheck disable=SC1091
. "$VENV_DIR/bin/activate"
set -u
cd "$PROJECT_DIR"
# Launch in the background, detached from the current terminal (nohup),
# so the server keeps running after the terminal is closed.
GRADIO_SERVER_PORT="$PORT" nohup python -m src.gui >> "$LOG_FILE" 2>&1 &
local pid=$!
echo "$pid" > "$PIDFILE"
# Wait until the port actually answers (or the process dies).
local attempts=0
while [ "$attempts" -lt 30 ]; do
if ! kill -0 "$pid" 2>/dev/null; then
echo "Server failed to start. Last log lines:" >&2
tail -n 20 "$LOG_FILE" 2>/dev/null >&2 || true
rm -f "$PIDFILE"
exit 1
fi
if is_server_running; then
echo "Server started at http://$(get_ip_address):$PORT (PID: $pid)"
echo " Log file: $LOG_FILE"
return 0
fi
sleep 1
attempts=$((attempts + 1))
done
echo "Timed out waiting for the server to start. Last log lines:" >&2
tail -n 20 "$LOG_FILE" 2>/dev/null >&2 || true
kill -TERM "$pid" 2>/dev/null || true
rm -f "$PIDFILE"
exit 1
}
# ------------------------------------------------------------
# stop
# ------------------------------------------------------------
stop_server() {
local pids
pids="$(port_pids | sort -u 2>/dev/null || true)"
# Secondary hint: trust a PID file entry only if that process exists.
if [ -z "$pids" ] && [ -f "$PIDFILE" ]; then
local oldpid
oldpid="$(cat "$PIDFILE" 2>/dev/null || true)"
if [ -n "$oldpid" ] && kill -0 "$oldpid" 2>/dev/null; then
pids="$oldpid"
fi
fi
if [ -z "$pids" ]; then
rm -f "$PIDFILE"
echo "No server was running"
return 0
fi
# Graceful stop: SIGTERM first.
for pid in $pids; do
kill -TERM "$pid" 2>/dev/null || true
done
# Give the server a few seconds to exit cleanly and free the port.
local attempts=0
while [ "$attempts" -lt 5 ]; do
is_server_running || break
sleep 1
attempts=$((attempts + 1))
done
# Force stop: SIGKILL anything still holding the port.
local remaining
remaining="$(port_pids | sort -u 2>/dev/null || true)"
if [ -n "$remaining" ]; then
echo " Did not stop in time — sending SIGKILL."
for pid in $remaining; do
kill -KILL "$pid" 2>/dev/null || true
done
sleep 1
fi
rm -f "$PIDFILE"
echo "Server stopped"
}
# ------------------------------------------------------------
# status
# ------------------------------------------------------------
status_server() {
local pids
pids="$(port_pids | sort -u 2>/dev/null || true)"
if [ -n "$pids" ]; then
local first
first="$(echo "$pids" | head -n 1)"
echo "Server is running on http://$(get_ip_address):$PORT (PID: $first)"
return 0
fi
if [ -f "$PIDFILE" ]; then
# Stale PID file from a previous run — clean it up.
rm -f "$PIDFILE"
fi
if kernel_has_listener; then
echo "Server is not running, but port $PORT is blocked by an orphaned LISTEN socket" >&2
return 1
fi
echo "Server is not running"
}
# ------------------------------------------------------------
# restart
# ------------------------------------------------------------
restart_server() {
stop_server
echo ""
start_server
}
# ------------------------------------------------------------
# dispatch
# ------------------------------------------------------------
usage() {
echo "Usage: $0 {start|stop|status|restart|help}"
echo ""
echo " start Start the Gradio server in the background"
echo " stop Stop the server (SIGTERM, then SIGKILL)"
echo " status Show whether the server is running"
echo " restart Stop, then start again"
echo " help Show this help"
echo ""
echo "The port can be overridden with GRADIO_SERVER_PORT (default: 7860)."
}
case "${1:-}" in
start) start_server ;;
stop) stop_server ;;
status) status_server ;;
restart) restart_server ;;
help|-h|--help) usage ;;
*)
echo "Unknown command: '${1:-}'" >&2
usage >&2
exit 1
;;
esac