File size: 20,870 Bytes
52013b5
 
4b49862
52013b5
269f150
0cdf7b0
269f150
 
52013b5
 
 
 
 
269f150
52013b5
 
 
 
 
 
 
a5f3eb0
52013b5
 
 
20de61f
52013b5
 
 
 
269f150
0cdf7b0
52013b5
269f150
a0dcc38
501b164
4b49862
08e5895
 
 
 
8bddfd6
0cdf7b0
 
 
 
 
 
 
269f150
501b164
269f150
 
 
08e5895
acafb8d
1a68ada
acafb8d
52013b5
a5f3eb0
52013b5
 
 
 
 
 
 
 
 
 
 
0db5b04
269f150
 
0db5b04
 
52013b5
 
 
a5f3eb0
52013b5
 
 
 
269f150
52013b5
 
 
 
 
 
 
 
 
 
 
269f150
 
 
52013b5
269f150
52013b5
269f150
52013b5
 
 
 
 
269f150
 
52013b5
269f150
 
 
 
 
52013b5
 
a5f3eb0
269f150
4b49862
52013b5
 
 
269f150
4b49862
52013b5
 
 
501b164
 
269f150
 
52013b5
269f150
52013b5
269f150
52013b5
 
269f150
501b164
269f150
 
501b164
 
269f150
501b164
 
269f150
4b49862
0cdf7b0
 
269f150
 
 
 
0cdf7b0
 
 
269f150
0db5b04
269f150
 
 
0db5b04
52013b5
269f150
 
52013b5
269f150
52013b5
269f150
52013b5
269f150
4b49862
b56f91e
269f150
 
 
 
 
4b49862
269f150
4b49862
52013b5
0cdf7b0
 
 
 
 
4b49862
0cdf7b0
 
 
 
 
 
1a68ada
 
08e5895
1a68ada
08e5895
1a68ada
 
 
 
 
 
 
 
 
 
 
08e5895
1a68ada
 
 
 
 
 
 
 
 
 
 
 
03209c8
 
 
0db5b04
9a274e2
 
0db5b04
9a274e2
 
 
 
 
 
 
 
 
 
 
 
 
 
0db5b04
269f150
 
4b49862
52013b5
 
a5f3eb0
52013b5
269f150
52013b5
 
 
 
4b49862
269f150
52013b5
269f150
 
 
 
 
 
0cdf7b0
 
 
 
 
 
4b49862
269f150
 
 
 
 
 
 
 
 
1a68ada
 
 
08e5895
1a68ada
 
 
 
 
 
 
 
 
 
 
 
 
 
08e5895
 
269f150
 
08e5895
269f150
 
 
 
52013b5
269f150
 
 
5c0994f
d111a78
08e5895
1a68ada
0cdf7b0
 
 
 
 
 
 
 
 
269f150
 
 
 
 
 
 
5c0994f
269f150
 
 
 
 
 
5c0994f
269f150
 
 
 
5c0994f
 
 
269f150
 
5c0994f
 
 
 
 
269f150
 
5c0994f
 
269f150
 
 
5c0994f
269f150
 
 
5c0994f
269f150
4b49862
5c0994f
 
a5f3eb0
269f150
52013b5
 
269f150
 
 
 
1a68ada
269f150
a5f3eb0
269f150
 
54cbddc
 
52013b5
54cbddc
269f150
20de61f
52013b5
 
 
a5f3eb0
52013b5
 
 
 
 
 
 
269f150
 
 
 
 
 
 
 
 
 
 
a5f3eb0
52013b5
269f150
52013b5
 
 
269f150
 
52013b5
269f150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52013b5
269f150
 
52013b5
269f150
 
 
 
 
 
52013b5
 
a5f3eb0
 
 
 
 
74dd2e2
 
a5f3eb0
 
4b49862
 
 
 
a5f3eb0
 
 
 
 
4b49862
 
 
 
 
0fd7ea3
 
4b49862
 
0fd7ea3
 
4b49862
0fd7ea3
4b49862
 
 
 
 
a5f3eb0
269f150
ca96613
 
269f150
ca96613
 
 
a5f3eb0
 
ca96613
 
 
 
 
 
269f150
52013b5
 
 
 
 
 
 
 
 
 
 
 
 
269f150
 
52013b5
 
 
 
 
 
ca96613
52013b5
269f150
 
52013b5
 
 
 
 
269f150
 
52013b5
 
 
269f150
 
 
 
52013b5
 
a5f3eb0
52013b5
 
4b49862
 
52013b5
ca96613
 
52013b5
 
 
a5f3eb0
52013b5
 
 
 
 
 
269f150
52013b5
 
 
 
 
80c4d9b
 
 
269f150
 
4b49862
269f150
80c4d9b
269f150
80c4d9b
 
 
d09e48b
269f150
 
4b49862
d09e48b
52013b5
 
 
 
 
 
269f150
 
52013b5
d09e48b
52013b5
 
 
 
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
#!/usr/bin/env python3
"""
HuggingRun v2 - Ubuntu Server on HuggingFace Spaces.

Persistence via HF Dataset (direct file sync, no archives):
  - Sync scope: /home, /root, /usr/local, /opt, /var/lib, /etc
  - System packages: saved as package name list, restored via apt install
  - Symlinks/permissions safe: no system binary dirs synced
"""

import http.server
import json
import os
import shutil
import signal
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone

# -- Config ------------------------------------------------------------
PERSIST_PATH = os.environ.get("PERSIST_PATH", "/data")
HF_TOKEN = os.environ.get("HF_TOKEN", "")
HF_DATASET_REPO = os.environ.get("HF_DATASET_REPO", "")
SYNC_INTERVAL = int(os.environ.get("SYNC_INTERVAL", "60"))
SSH_PORT = os.environ.get("SSH_PORT", "2222")
TTYD_PORT = os.environ.get("TTYD_PORT", "7681")
LOGFILE = "/var/log/huggingrun.log"
BASE_PKG_FILE = "/etc/base-packages.list"
PKG_FILE = os.path.join(PERSIST_PATH, "user-packages.list")
PIP_FILE = os.path.join(PERSIST_PATH, "pip-packages.txt")

# Directories to sync (user data only, no system binaries)
SYNC_DIRS = ["/home", "/root", "/usr/local", "/opt", "/var/lib", "/var/log", "/etc"]

# Exclude from rsync (relative paths - rsync matches from transfer root)
RSYNC_EXCLUDES = [
    "*.sock", "*.pid", "*.lock", "huggingrun.log",
    ".cursor-server", ".vscode-server",  # IDE servers: huge, reinstallable
]

# Extra excludes only for /etc/ restore (container-managed files)
ETC_RESTORE_EXCLUDES = [
    "hostname", "hosts", "resolv.conf", "mtab", "fstab",
    "alternatives",     # symlinks managed by dpkg
    "ld.so.cache",      # rebuilt by ldconfig
]

# Exclude from HF upload
UPLOAD_IGNORE = [
    "__pycache__", "*.pyc", ".git", ".git*",
    "*.sock", "*.lock", ".huggingface", ".cache",
    "huggingrun.env",       # contains HF_TOKEN
    ".cursor-server", ".vscode-server",
]
PERM_MANIFEST = os.path.join(PERSIST_PATH, "perm-manifest.txt")


# -- Logging -----------------------------------------------------------
def log(msg):
    ts = time.strftime("%H:%M:%S", time.gmtime())
    line = f"[{ts}] {msg}"
    print(line, file=sys.stderr, flush=True)
    try:
        with open(LOGFILE, "a") as f:
            f.write(line + "\n")
    except Exception:
        pass


def sh(cmd, log_err=False):
    """Run shell command, return (exit_code, stdout)."""
    r = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    if log_err and r.returncode != 0 and r.stderr:
        log(f"  cmd error: {r.stderr.strip()[:200]}")
    return r.returncode, (r.stdout or "").strip()


# -- Config Resolution -------------------------------------------------
def resolve_config():
    global HF_TOKEN, HF_DATASET_REPO
    HF_TOKEN = os.environ.get("HF_TOKEN", "")
    if not HF_DATASET_REPO:
        space_id = os.environ.get("SPACE_ID", "")
        if space_id:
            HF_DATASET_REPO = f"{space_id}-data"
        elif HF_TOKEN:
            try:
                from huggingface_hub import HfApi
                name = HfApi(token=HF_TOKEN).whoami()["name"]
                HF_DATASET_REPO = f"{name}/HuggingRun-data"
            except Exception:
                pass
        os.environ["HF_DATASET_REPO"] = HF_DATASET_REPO

    log("=" * 50)
    log("HuggingRun v2")
    log(f"  HF_TOKEN: {'set' if HF_TOKEN else 'NOT SET'}")
    log(f"  HF_DATASET_REPO: {HF_DATASET_REPO or 'NOT SET'}")
    log(f"  SYNC_DIRS: {SYNC_DIRS}")
    log(f"  SYNC_INTERVAL: {SYNC_INTERVAL}s")
    log("=" * 50)


def ensure_dataset_repo():
    if not HF_TOKEN or not HF_DATASET_REPO:
        return
    from huggingface_hub import HfApi
    api = HfApi(token=HF_TOKEN)
    try:
        api.repo_info(repo_id=HF_DATASET_REPO, repo_type="dataset")
        log(f"dataset: {HF_DATASET_REPO}")
    except Exception:
        api.create_repo(repo_id=HF_DATASET_REPO, repo_type="dataset", private=True)
        log(f"created dataset: {HF_DATASET_REPO}")


# -- Restore -----------------------------------------------------------
def restore():
    """Download dataset -> rsync to / -> reinstall apt packages."""
    if not HF_TOKEN or not HF_DATASET_REPO:
        return

    # Download dataset
    log("[restore] downloading dataset")
    os.makedirs(PERSIST_PATH, exist_ok=True)
    t0 = time.time()
    try:
        from huggingface_hub import snapshot_download
        snapshot_download(
            repo_id=HF_DATASET_REPO, repo_type="dataset",
            local_dir=PERSIST_PATH, token=HF_TOKEN,
        )
        log(f"  downloaded ({time.time()-t0:.1f}s)")
    except Exception as e:
        log(f"  download failed: {e}")
        return

    # Check if there's data to restore
    has_data = any(
        os.path.isdir(os.path.join(PERSIST_PATH, d.lstrip("/")))
        for d in SYNC_DIRS
    )
    if not has_data:
        log("  empty dataset, fresh start")
        return

    # Rsync each directory back (no --delete, don't remove existing files)
    log("[restore] rsync /data/ -> /")
    base_excludes = " ".join(f"--exclude='{e}'" for e in RSYNC_EXCLUDES)
    etc_excludes = " ".join(f"--exclude='{e}'" for e in ETC_RESTORE_EXCLUDES)
    for d in SYNC_DIRS:
        src = os.path.join(PERSIST_PATH, d.lstrip("/"))
        if not os.path.isdir(src):
            continue
        excludes = base_excludes
        if d == "/etc":
            excludes = f"{base_excludes} {etc_excludes}"
        cmd = f"rsync -rlptD {excludes} '{src}/' '{d}/'"
        rc, _ = sh(cmd, log_err=True)
        if rc == 0:
            log(f"  {d}/ restored")
        else:
            log(f"  {d}/ restore failed (rc={rc})")

    # Reinstall apt packages
    if os.path.exists(PKG_FILE) and os.path.exists(BASE_PKG_FILE):
        with open(BASE_PKG_FILE) as f:
            base = set(f.read().split())
        with open(PKG_FILE) as f:
            saved = set(f.read().split())
        to_install = sorted(saved - base)
        if to_install:
            log(f"[restore] apt install {len(to_install)} packages")
            rc, _ = sh(f"apt-get update -qq && apt-get install -y --reinstall --no-install-recommends {' '.join(to_install)}")
            if rc == 0:
                log(f"  packages restored")
            else:
                log(f"  some packages failed")
        else:
            log("[restore] no extra packages")
    else:
        log("[restore] no package list")

    # Reinstall pip packages
    if os.path.exists(PIP_FILE):
        with open(PIP_FILE) as f:
            pip_pkgs = [l.strip() for l in f if l.strip() and not l.startswith('#')]
        if pip_pkgs:
            log(f"[restore] pip install {len(pip_pkgs)} packages")
            rc, _ = sh(f"pip install --break-system-packages -q -r '{PIP_FILE}'")
            if rc == 0:
                log(f"  pip packages restored")
            else:
                log(f"  some pip packages failed")

    # Restore file permissions from manifest (HF dataset resets all to 0644/0755)
    if os.path.exists(PERM_MANIFEST):
        count = 0
        with open(PERM_MANIFEST) as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                parts = line.split(' ', 1)
                if len(parts) != 2:
                    continue
                mode_str, path = parts
                try:
                    mode = int(mode_str, 8)
                    if os.path.exists(path):
                        os.chmod(path, mode)
                        count += 1
                except (ValueError, OSError):
                    pass
        log(f"  restored permissions on {count} files")

    # Fix SSH permissions explicitly (belt + suspenders)
    for home in ["/home/tao-shen", "/root"]:
        ssh_dir = os.path.join(home, ".ssh")
        if os.path.isdir(ssh_dir):
            os.chmod(ssh_dir, 0o700)
            ak = os.path.join(ssh_dir, "authorized_keys")
            if os.path.exists(ak):
                os.chmod(ak, 0o600)
    sh("chmod 600 /etc/ssh/ssh_host_*_key 2>/dev/null")
    sh("chmod 644 /etc/ssh/ssh_host_*_key.pub 2>/dev/null")

    # Restart sshd to pick up restored host keys
    sh("pkill sshd")
    time.sleep(1)
    os.makedirs("/run/sshd", exist_ok=True)
    proc = subprocess.Popen([
        "/usr/sbin/sshd", "-D", "-e",
        "-o", f"Port={SSH_PORT}",
        "-o", "ListenAddress=127.0.0.1",
        "-o", "PermitRootLogin=yes",
        "-o", "PasswordAuthentication=yes",
        "-o", "PermitEmptyPasswords=no",
        "-o", "UsePAM=yes",
    ])
    time.sleep(0.5)
    if proc.poll() is None:
        log(f"  sshd restarted ok PID={proc.pid}")
    else:
        log(f"  sshd restart FAILED (exit={proc.poll()})")

    # Fix up after restore
    sh('ldconfig 2>/dev/null')
    log("[restore] complete")


# -- Save + Upload -----------------------------------------------------
def save_and_upload():
    """Rsync sync dirs to /data/, then upload to HF dataset."""
    if not HF_TOKEN or not HF_DATASET_REPO:
        return
    from huggingface_hub import HfApi

    log("[sync] start")
    t0_total = time.time()

    # Save apt package list
    rc, out = sh("dpkg-query -W -f='${Package}\\n'")
    if rc == 0 and out:
        with open(PKG_FILE, "w") as f:
            f.write(out + "\n")

    # Save pip package list (user-installed only, exclude base)
    rc, out = sh("pip freeze --exclude-editable 2>/dev/null")
    if rc == 0 and out:
        with open(PIP_FILE, "w") as f:
            f.write(out + "\n")

    # Rsync each sync dir -> /data/
    excludes = " ".join(f"--exclude='{e}'" for e in RSYNC_EXCLUDES)
    for d in SYNC_DIRS:
        if not os.path.isdir(d):
            continue
        dst = os.path.join(PERSIST_PATH, d.lstrip("/"))
        os.makedirs(dst, exist_ok=True)
        cmd = f"rsync -rlptD --delete {excludes} '{d}/' '{dst}/'"
        sh(cmd)

    # Save full permission manifest (HF dataset resets all to 0644/0755)
    # Capture all files/dirs with non-default permissions
    perm_entries = []
    for d in SYNC_DIRS:
        if not os.path.isdir(d):
            continue
        rc, out = sh(
            f"find '{d}' -not -path '*/.cursor-server/*' -not -path '*/.vscode-server/*' "
            f"-not -path '*/.cache/*' "
            f"\\( \\( -type f -not -perm 644 \\) -o \\( -type d -not -perm 755 \\) \\) "
            f"-printf '%m %p\\n' 2>/dev/null"
        )
        if rc == 0 and out:
            perm_entries.extend(out.strip().split('\n'))
    if perm_entries:
        with open(PERM_MANIFEST, "w") as f:
            f.write('\n'.join(perm_entries) + '\n')
        log(f"  saved {len(perm_entries)} permission entries")

    # Clean dirs that should not be uploaded
    for dirpath, dirnames, _ in os.walk(PERSIST_PATH):
        for dn in list(dirnames):
            if dn in (".cache", ".cursor-server", ".vscode-server"):
                shutil.rmtree(os.path.join(dirpath, dn), ignore_errors=True)
                dirnames.remove(dn)

    # Upload each directory to HF dataset
    api = HfApi(token=HF_TOKEN)
    ts = time.strftime("%Y-%m-%d %H:%M", time.gmtime())
    ok = 0
    fail = 0

    # Upload package list files + log
    for pf, name in [(PKG_FILE, "user-packages.list"), (PIP_FILE, "pip-packages.txt"),
                     (PERM_MANIFEST, "perm-manifest.txt"), (LOGFILE, "huggingrun.log")]:
        if os.path.exists(pf):
            try:
                api.upload_file(
                    path_or_fileobj=pf, path_in_repo=name,
                    repo_id=HF_DATASET_REPO, repo_type="dataset",
                    commit_message=f"sync {ts}: {name}",
                )
            except Exception:
                pass

    # Upload each sync dir
    for d in SYNC_DIRS:
        local = os.path.join(PERSIST_PATH, d.lstrip("/"))
        if not os.path.isdir(local):
            continue
        repo_path = d.lstrip("/")

        # Count files
        try:
            fc = int(subprocess.check_output(
                f"find '{local}' -type f | wc -l", shell=True, text=True).strip())
        except Exception:
            fc = 0
        if fc == 0:
            continue

        # Upload with retry
        for attempt in range(3):
            t0 = time.time()
            try:
                api.upload_folder(
                    folder_path=local,
                    repo_id=HF_DATASET_REPO, repo_type="dataset",
                    path_in_repo=repo_path,
                    commit_message=f"sync {ts}: {repo_path}/",
                    ignore_patterns=UPLOAD_IGNORE,
                )
                log(f"  {repo_path}/ ok ({time.time()-t0:.1f}s, {fc} files)")
                ok += 1
                break
            except Exception as e:
                err = str(e).split('\n')[0][:100]
                if attempt < 2:
                    log(f"  {repo_path}/ retry {attempt+1}: {err}")
                    time.sleep((attempt + 1) * 5)
                else:
                    log(f"  {repo_path}/ FAILED: {err}")
                    fail += 1
        time.sleep(2)  # rate limit between dirs

    elapsed = time.time() - t0_total
    log(f"[sync] done ({elapsed:.1f}s) {ok} ok, {fail} failed")


# -- Background Threads ------------------------------------------------
restore_done = threading.Event()


def background_restore():
    try:
        restore()
        ensure_passwords()
        setup_motd()  # re-apply after restore overwrites /etc/
    except Exception as e:
        log(f"[restore] error: {e}")
    finally:
        restore_done.set()


def sync_loop():
    restore_done.wait()
    log("sync: ready, first sync in 30s")
    time.sleep(30)
    cycle = 0
    while True:
        cycle += 1
        log(f"[sync] #{cycle}")
        try:
            save_and_upload()
        except Exception as e:
            log(f"  sync error: {e}")
        time.sleep(SYNC_INTERVAL)


def heartbeat_loop():
    while True:
        time.sleep(60)
        try:
            _, load = sh("cat /proc/loadavg | cut -d' ' -f1-3")
            _, mem = sh("free -h | grep Mem: | tr -s ' ' | cut -d' ' -f2,3 | sed 's/ /\\//'")
            log(f"heartbeat: load={load} mem={mem}")
        except Exception:
            pass


# -- Log Streamer (SSE on port 7863) ----------------------------------
class LogSSEHandler(http.server.BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def do_GET(self):
        if self.path != "/stream":
            self.send_response(404)
            self.end_headers()
            return
        self.send_response(200)
        self.send_header("Content-Type", "text/event-stream")
        self.send_header("Cache-Control", "no-cache")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.end_headers()
        try:
            with open(LOGFILE) as f:
                # Send existing log
                for line in f:
                    line = line.rstrip("\n")
                    if line:
                        ev = json.dumps({"data": line})
                        self.wfile.write(f"data: {ev}\n\n".encode())
                        self.wfile.flush()
                # Tail new lines
                while True:
                    line = f.readline()
                    if line:
                        line = line.rstrip("\n")
                        if line:
                            ev = json.dumps({"data": line})
                            self.wfile.write(f"data: {ev}\n\n".encode())
                            self.wfile.flush()
                    else:
                        self.wfile.write(b": keepalive\n\n")
                        self.wfile.flush()
                        time.sleep(1)
        except (BrokenPipeError, ConnectionResetError):
            pass


# -- Service Management ------------------------------------------------
def setup_motd():
    """Replace Ubuntu MOTD with clean HuggingRun banner."""
    sh("chmod -x /etc/update-motd.d/* 2>/dev/null")
    sh("rm -f /run/motd.dynamic")
    # Clear Ubuntu legal notice
    open("/etc/legal", "w").close()
    motd = (
        "\n"
        "\x1b[38;5;39m"
        "  H U G G I N G R U N\x1b[0m  \x1b[90mv2\x1b[0m\n"
        "  \x1b[90mUbuntu Server on HuggingFace Spaces\x1b[0m\n"
        "  \x1b[90m" + "-" * 40 + "\x1b[0m\n"
        "\n"
    )
    with open("/etc/motd", "w") as f:
        f.write(motd)

    # Suppress "To run a command as administrator" sudo hint
    sh("touch /home/tao-shen/.sudo_as_admin_successful")
    sh("chown tao-shen:tao-shen /home/tao-shen/.sudo_as_admin_successful")

    # Set PS1 with custom hostname (Docker container hostname is unreadable)
    # Skip PS1 override when VS Code/Cursor shell integration is active,
    # as it injects OSC markers into PS1 for command detection.
    profile = (
        '#!/bin/bash\n'
        'if [ -z "$VSCODE_SHELL_INTEGRATION" ]; then\n'
        '  export PS1="\\[\\e[1;32m\\]\\u\\[\\e[0m\\]@\\[\\e[1;36m\\]huggingrun'
        '\\[\\e[0m\\]:\\[\\e[1;34m\\]\\w\\[\\e[0m\\]\\$ "\n'
        'fi\n'
    )
    with open("/etc/profile.d/huggingrun.sh", "w") as f:
        f.write(profile)
    sh("chmod +x /etc/profile.d/huggingrun.sh")


def ensure_passwords():
    sh("id tao-shen >/dev/null 2>&1 || useradd -m -s /bin/bash tao-shen")
    sh('echo "tao-shen:huggingrun" | chpasswd')
    sh('echo "root:huggingrun" | chpasswd')
    sh("usermod -aG sudo tao-shen 2>/dev/null || true")
    sh("echo 'tao-shen ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/tao-shen")
    sh("chmod 440 /etc/sudoers.d/tao-shen")
    # Fix home dir ownership recursively (restore may bring old uid mapping)
    sh("chown -R tao-shen:tao-shen /home/tao-shen")
    # Copy root's SSH keys to tao-shen if needed
    if os.path.exists("/root/.ssh/authorized_keys"):
        sh("mkdir -p /home/tao-shen/.ssh")
        sh("cp -n /root/.ssh/authorized_keys /home/tao-shen/.ssh/authorized_keys 2>/dev/null || true")
        sh("chown -R tao-shen:tao-shen /home/tao-shen/.ssh")
        sh("chmod 700 /home/tao-shen/.ssh && chmod 600 /home/tao-shen/.ssh/authorized_keys")
    sh("ldconfig 2>/dev/null || true")


def start_sshd():
    os.makedirs("/run/sshd", exist_ok=True)
    proc = subprocess.Popen([
        "/usr/sbin/sshd", "-D", "-e",
        "-o", f"Port={SSH_PORT}",
        "-o", "ListenAddress=127.0.0.1",
        "-o", "PermitRootLogin=yes",
        "-o", "PasswordAuthentication=yes",
        "-o", "PermitEmptyPasswords=no",
        "-o", "UsePAM=yes",
    ])
    time.sleep(0.5)
    log(f"[OK] sshd PID={proc.pid}" if proc.poll() is None else "[FAIL] sshd")
    return proc


def start_ttyd():
    proc = subprocess.Popen([
        "ttyd", "--port", TTYD_PORT, "--writable", "--base-path", "/",
        "login", "-f", "tao-shen",
    ])
    time.sleep(0.5)
    log(f"[OK] ttyd PID={proc.pid}" if proc.poll() is None else "[FAIL] ttyd")
    return proc


def start_ws_bridge():
    proc = subprocess.Popen([sys.executable, "/ws_ssh_bridge.py"])
    time.sleep(0.5)
    log(f"[OK] ws-bridge PID={proc.pid}" if proc.poll() is None else "[FAIL] ws-bridge")
    return proc


def start_log_streamer():
    srv = http.server.HTTPServer(("127.0.0.1", 7863), LogSSEHandler)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    log("[OK] log-streamer :7863")


# -- Main --------------------------------------------------------------
def main():
    os.makedirs(PERSIST_PATH, exist_ok=True)
    # Truncate log on startup (old log may have encoding artifacts from restore)
    open(LOGFILE, "w").close()

    sh("hostname huggingrun")

    resolve_config()
    ensure_dataset_repo()
    ensure_passwords()
    setup_motd()

    # Write env for other processes
    with open("/etc/huggingrun.env", "w") as f:
        f.write(f'export HF_TOKEN="{HF_TOKEN}"\n')
        f.write(f'export HF_DATASET_REPO="{HF_DATASET_REPO}"\n')

    # Start services (open port 7860 ASAP to avoid HF timeout)
    start_sshd()
    start_ws_bridge()
    start_ttyd()
    start_log_streamer()

    nginx_proc = subprocess.Popen(
        ["nginx", "-c", "/etc/nginx/nginx.conf", "-g", "daemon off;"]
    )
    log(f"[OK] nginx PID={nginx_proc.pid}")
    log("=" * 50)
    log("READY - restore runs in background")
    log("=" * 50)

    # Background restore + sync
    threading.Thread(target=background_restore, daemon=True).start()
    threading.Thread(target=sync_loop, daemon=True).start()
    threading.Thread(target=heartbeat_loop, daemon=True).start()

    # Graceful shutdown
    def on_signal(sig, frame):
        log(f"signal {sig} - final save")
        nginx_proc.terminate()
        try:
            save_and_upload()
        except Exception as e:
            log(f"final save error: {e}")
        sys.exit(0)

    signal.signal(signal.SIGTERM, on_signal)
    signal.signal(signal.SIGINT, on_signal)

    nginx_proc.wait()


if __name__ == "__main__":
    main()