Eric Xu commited on
Commit
2a7b950
·
unverified ·
1 Parent(s): d00cf52

Fix port binding crash: kill zombie process and enable SO_REUSEADDR

Browse files
Files changed (1) hide show
  1. web/app.py +16 -1
web/app.py CHANGED
@@ -885,8 +885,23 @@ async def get_results(sid: str):
885
 
886
  if __name__ == "__main__":
887
  import uvicorn
 
 
888
  port = int(os.getenv("PORT", "7860" if IS_SPACES else "8000"))
889
  host = "0.0.0.0" if IS_SPACES else "127.0.0.1"
 
 
 
 
 
 
890
  print(f"\n SGO Web Interface")
891
  print(f" http://{host}:{port}\n")
892
- uvicorn.run(app, host=host, port=port, access_log=False)
 
 
 
 
 
 
 
 
885
 
886
  if __name__ == "__main__":
887
  import uvicorn
888
+ import socket
889
+
890
  port = int(os.getenv("PORT", "7860" if IS_SPACES else "8000"))
891
  host = "0.0.0.0" if IS_SPACES else "127.0.0.1"
892
+
893
+ # Kill any process holding the port (HF Spaces restarts can leave zombies)
894
+ if IS_SPACES:
895
+ import subprocess
896
+ subprocess.run(f"fuser -k {port}/tcp", shell=True, capture_output=True)
897
+
898
  print(f"\n SGO Web Interface")
899
  print(f" http://{host}:{port}\n")
900
+
901
+ config = uvicorn.Config(app, host=host, port=port, access_log=False)
902
+ server = uvicorn.Server(config)
903
+ # Enable SO_REUSEADDR so restarts don't fail on TIME_WAIT sockets
904
+ config.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
905
+ config.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
906
+ config.socket.bind((host, port))
907
+ server.run()