akseljoonas HF Staff commited on
Commit
9c6f4b2
·
1 Parent(s): d95cff9

Retry port binding in start.sh for dev mode restarts

Browse files
Files changed (1) hide show
  1. backend/start.sh +29 -13
backend/start.sh CHANGED
@@ -1,15 +1,31 @@
1
  #!/bin/bash
2
  # Entrypoint for HF Spaces dev mode compatibility.
3
- # Dev mode spawns CMD multiple times simultaneously on restart.
4
- # Only the first instance can bind port 7860 the rest must exit
5
- # with code 0 so the dev mode daemon doesn't mark the app as crashed.
6
-
7
- # Run uvicorn; if it fails due to port conflict, exit cleanly.
8
- uvicorn main:app --host 0.0.0.0 --port 7860
9
- EXIT_CODE=$?
10
-
11
- if [ $EXIT_CODE -ne 0 ]; then
12
- # Check if this was a port-in-use failure (another instance already running)
13
- echo "uvicorn exited with code $EXIT_CODE, exiting gracefully."
14
- exit 0
15
- fi
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  #!/bin/bash
2
  # Entrypoint for HF Spaces dev mode compatibility.
3
+ # Dev mode spawns multiple CMD instances simultaneously on restart.
4
+ # The old process may still hold port 7860 briefly, so we retry
5
+ # with backoff until the port is free.
6
+
7
+ MAX_RETRIES=5
8
+ RETRY_DELAY=2
9
+
10
+ for i in $(seq 1 $MAX_RETRIES); do
11
+ uvicorn main:app --host 0.0.0.0 --port 7860
12
+ EXIT_CODE=$?
13
+
14
+ if [ $EXIT_CODE -eq 0 ]; then
15
+ exit 0
16
+ fi
17
+
18
+ # Check if another instance from this restart batch is already running
19
+ if ss -tlnp 2>/dev/null | grep -q ":7860 "; then
20
+ echo "Port 7860 already bound by another instance, exiting."
21
+ exit 0
22
+ fi
23
+
24
+ if [ $i -lt $MAX_RETRIES ]; then
25
+ echo "uvicorn exited ($EXIT_CODE), retrying in ${RETRY_DELAY}s (attempt $i/$MAX_RETRIES)..."
26
+ sleep $RETRY_DELAY
27
+ fi
28
+ done
29
+
30
+ echo "Failed to bind port 7860 after $MAX_RETRIES attempts."
31
+ exit 1