-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart_server.py
More file actions
125 lines (97 loc) · 2.43 KB
/
Copy pathstart_server.py
File metadata and controls
125 lines (97 loc) · 2.43 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
import os
os.environ["MPLBACKEND"] = "Agg"
import platform
import re
import shutil
import subprocess
import time
import urllib.request
from pathlib import Path
import requests
REPO = Path(__file__).resolve().parent
PYTHON = REPO / ".venv/bin/python"
LOCAL_URL = "http://127.0.0.1:8000"
def get_cloudflared():
existing = shutil.which("cloudflared")
if existing:
return existing
if platform.machine() not in {"x86_64", "AMD64"}:
raise RuntimeError(
f"Unsupported architecture: {platform.machine()}"
)
install_path = Path("/usr/local/bin/cloudflared")
download_url = (
"https://github.com/cloudflare/cloudflared/"
"releases/latest/download/cloudflared-linux-amd64"
)
print("Installing cloudflared...")
urllib.request.urlretrieve(
download_url,
install_path,
)
install_path.chmod(0o755)
return str(install_path)
cloudflared = get_cloudflared()
server_process = subprocess.Popen(
[
str(PYTHON),
"-m",
"uvicorn",
"demo.main:app",
"--host",
"0.0.0.0",
"--port",
"8000",
],
cwd=REPO,
)
print("Waiting for server...")
for attempt in range(180):
if server_process.poll() is not None:
raise RuntimeError(
f"Uvicorn exited with code "
f"{server_process.returncode}"
)
try:
response = requests.get(
f"{LOCAL_URL}/docs",
timeout=2,
)
if response.ok:
break
except requests.RequestException:
pass
if attempt % 12 == 0:
print(f"Still loading... {attempt * 5}s")
time.sleep(5)
else:
server_process.terminate()
raise RuntimeError("Server startup timed out.")
print("Server ready.")
tunnel_process = subprocess.Popen(
[
cloudflared,
"tunnel",
"--url",
LOCAL_URL,
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
try:
for line in tunnel_process.stdout:
print(line, end="")
match = re.search(
r"https://[-a-z0-9]+\.trycloudflare\.com",
line,
)
if match:
print("\nPublic URL:", match.group(0))
except KeyboardInterrupt:
print("\nStopping server and tunnel...")
finally:
for process in (tunnel_process, server_process):
if process.poll() is None:
process.terminate()