-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathgithub_update.py
More file actions
executable file
·302 lines (248 loc) · 8.52 KB
/
github_update.py
File metadata and controls
executable file
·302 lines (248 loc) · 8.52 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
#!/usr/bin/env python3
"""Self-update this repository using GitHub ZIP archives.
The script checks the last seen commit SHA in ``last_sha.txt`` and compares it
with the latest commit on ``main`` fetched via the GitHub API. If a newer
commit is available, the corresponding ZIP archive is downloaded and unpacked
over the current project directory. The new SHA is then stored in
``last_sha.txt`` and the local webserver is restarted. If ``requirements.txt``
changed, the script runs ``pip install --no-cache-dir -r requirements.txt``
after setting ``TMPDIR=/data/UserData/tmp`` before restarting the server.
Set the environment variable ``GITHUB_REPO`` to ``owner/repo`` (defaults to
``charlesvestal/extending-move``) before running if you need to override the
repository.
"""
from __future__ import annotations
import io
import os
import shutil
import sys
import tempfile
import zipfile
from pathlib import Path
import hashlib
import argparse
import requests
import subprocess
import signal
import time
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
def _headers() -> dict | None:
if GITHUB_TOKEN:
return {"Authorization": f"token {GITHUB_TOKEN}"}
return None
# Allow overrides for repository and default branch via environment
REPO = os.environ.get("GITHUB_REPO", "charlesvestal/extending-move")
ROOT_DIR = Path(__file__).resolve().parents[1]
DEFAULT_BRANCH = os.environ.get("GITHUB_BRANCH", "main")
SHA_FILE = ROOT_DIR / "last_sha.txt"
BRANCH_FILE = ROOT_DIR / "last_branch.txt"
# Directory for temporary extraction; defaults to repo root if not provided
TMP_DIR_PATH = Path(
os.environ.get("UPDATE_TMPDIR")
or os.environ.get("TMPDIR", str(ROOT_DIR))
)
def read_last_sha() -> str:
try:
return SHA_FILE.read_text().strip()
except FileNotFoundError:
return ""
def write_last_sha(sha: str) -> None:
SHA_FILE.write_text(f"{sha}\n")
def read_last_branch() -> str:
try:
return BRANCH_FILE.read_text().strip()
except FileNotFoundError:
return DEFAULT_BRANCH
def write_last_branch(branch: str) -> None:
BRANCH_FILE.write_text(f"{branch}\n")
def fetch_latest_sha(repo: str, branch: str = DEFAULT_BRANCH) -> str | None:
url = f"https://api.github.com/repos/{repo}/commits/{branch}"
headers = _headers()
try:
resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()
return resp.json().get("sha")
except Exception as exc: # noqa: BLE001
print(f"Error fetching latest SHA: {exc}", file=sys.stderr)
return None
def download_zip(repo: str, branch: str = DEFAULT_BRANCH) -> bytes | None:
url = f"https://github.com/{repo}/archive/refs/heads/{branch}.zip"
headers = _headers()
try:
resp = requests.get(url, headers=headers, timeout=20)
resp.raise_for_status()
return resp.content
except Exception as exc: # noqa: BLE001
print(f"Error downloading ZIP archive: {exc}", file=sys.stderr)
return None
def _hash_file(path: Path) -> str | None:
if not path.exists():
return None
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
return h.hexdigest()
def _fix_bin_permissions(root: Path) -> None:
"""Ensure files in ``root/bin`` are executable."""
bin_dir = root / "bin"
if not bin_dir.exists():
return
for path in bin_dir.rglob("*"):
if path.is_file() or path.is_dir():
try:
path.chmod(0o755)
except Exception as exc: # noqa: BLE001
print(f"Error setting permissions for {path}: {exc}", file=sys.stderr)
def overlay_from_zip(content: bytes, root: Path) -> bool:
"""Return ``True`` if ``requirements.txt`` changed."""
with tempfile.TemporaryDirectory(dir=str(TMP_DIR_PATH)) as tmpdir:
with zipfile.ZipFile(io.BytesIO(content)) as zf:
zf.extractall(tmpdir)
extracted_root = next(Path(tmpdir).iterdir())
old_hash = _hash_file(root / "requirements.txt")
new_hash = _hash_file(extracted_root / "requirements.txt")
shutil.copytree(extracted_root, root, dirs_exist_ok=True)
_fix_bin_permissions(root)
return old_hash != new_hash
def install_requirements(root: Path) -> None:
req = root / "requirements.txt"
if not req.exists():
return
env = os.environ.copy()
env.setdefault("TMPDIR", "/data/UserData/tmp")
print(f"TMPDIR is set to: {env['TMPDIR']}")
try:
subprocess.run(
[sys.executable, "-m", "pip", "install", "--no-cache-dir", "-r", str(req)],
check=True,
env=env,
)
except Exception as exc: # noqa: BLE001
print(f"Error installing requirements: {exc}", file=sys.stderr)
def restart_webserver(log: io.TextIOBase | None = None) -> None:
pid_file = ROOT_DIR / "move-webserver.pid"
log_file = ROOT_DIR / "move-webserver.log"
port_file = ROOT_DIR / "port.conf"
def log_msg(msg: str) -> None:
if log is not None:
log.write(msg + "\n")
log.flush()
else:
print(msg)
log_msg("Restarting the webserver...")
pid = None
if pid_file.exists():
try:
pid = int(pid_file.read_text().strip())
os.kill(pid, signal.SIGTERM)
except Exception:
pass
for _ in range(10):
try:
os.kill(pid, 0)
time.sleep(1)
except Exception:
break
try:
pid_file.unlink()
except Exception:
pass
else:
subprocess.run(["pkill", "-f", "move-webserver.py"], check=False)
if log_file.exists():
log_file.unlink()
env = os.environ.copy()
env.setdefault("PYTHONPATH", str(ROOT_DIR))
port = 909
try:
if port_file.exists():
value = int(port_file.read_text().strip())
if 0 < value < 65536:
port = value
except Exception:
pass
with open(log_file, "wb") as log_f:
subprocess.Popen(
["python3", "-u", str(ROOT_DIR / "move-webserver.py")],
cwd=ROOT_DIR,
stdout=log_f,
stderr=log_f,
env=env,
)
log_msg("Starting the webserver...")
new_pid = None
for _ in range(10):
if pid_file.exists():
try:
new_pid = int(pid_file.read_text().strip())
break
except Exception:
pass
time.sleep(1)
if not new_pid:
log_msg("Error: PID file not created. Check logs:")
if log_file.exists():
with open(log_file, "r", encoding="utf-8") as lf:
log_msg(lf.read())
raise RuntimeError("Server failed to start")
try:
os.kill(new_pid, 0)
except Exception:
log_msg("Error: Server failed to start. Check logs:")
if log_file.exists():
with open(log_file, "r", encoding="utf-8") as lf:
log_msg(lf.read())
raise RuntimeError("Server failed to start")
log_msg(f"Webserver restarted on port {port} with PID {new_pid}")
def update() -> int:
branch = read_last_branch()
last_sha = read_last_sha()
latest_sha = fetch_latest_sha(REPO, branch)
if not latest_sha:
return 1
if last_sha == latest_sha:
print("Already up-to-date.")
return 0
content = download_zip(REPO, branch)
if not content:
return 1
try:
changed = overlay_from_zip(content, ROOT_DIR)
except Exception as exc: # noqa: BLE001
print(f"Error unpacking ZIP: {exc}", file=sys.stderr)
return 1
write_last_sha(latest_sha)
write_last_branch(branch)
print(f"Updated to {latest_sha}")
if changed:
install_requirements(ROOT_DIR)
restart_webserver()
return 0
def main() -> int:
parser = argparse.ArgumentParser(description="Repository update utilities")
parser.add_argument(
"--restart-only",
action="store_true",
help="Only restart the webserver",
)
parser.add_argument(
"--log",
type=str,
default=None,
help="Path to log file for restart output",
)
args = parser.parse_args()
log: io.TextIOBase | None = None
if args.log:
log = open(args.log, "a", encoding="utf-8")
try:
if args.restart_only:
restart_webserver(log)
return 0
return update()
finally:
if log:
log.close()
if __name__ == "__main__":
sys.exit(main())