-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathconfigure_openchai_manager.py
More file actions
1697 lines (1346 loc) · 53.1 KB
/
Copy pathconfigure_openchai_manager.py
File metadata and controls
1697 lines (1346 loc) · 53.1 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
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Script Name : configure_openchai_manager.py
Purpose : Configure OpenCHAI manager tool for cluster setup
Author : Satish Gupta
Python Port : Optimized CLI version with rich UX
"""
from __future__ import annotations
import os
import sys
import shutil
import subprocess
import re
import logging
import platform
import urllib.request
import urllib.error
import urllib.parse
import base64
import getpass
import ssl
import tarfile
from dataclasses import dataclass
from pathlib import Path
from html.parser import HTMLParser
from typing import Dict, List, Optional, Set, Tuple
# ─────────────────────────────────────────────
# Dependency bootstrap (rich for UX)
# ─────────────────────────────────────────────
def _ensure_rich():
try:
import rich # noqa: F401
except ImportError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "rich", "--quiet"])
_ensure_rich()
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt, Confirm
from rich.table import Table
from rich import box
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, DownloadColumn, TransferSpeedColumn, TimeRemainingColumn
from rich.text import Text
from rich.rule import Rule
from rich.syntax import Syntax
console = Console()
# ─────────────────────────────────────────────
# Logging Setup
# ─────────────────────────────────────────────
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_LOG = Path("/var/log/openchai_config.log")
def _get_log_path() -> Path:
if DEFAULT_LOG.parent.exists() and os.access(DEFAULT_LOG.parent, os.W_OK):
return DEFAULT_LOG
return SCRIPT_DIR / "openchai_config.log"
LOG_PATH = _get_log_path()
logging.basicConfig(
filename=str(LOG_PATH),
level=logging.DEBUG,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
log = logging.getLogger("openchai")
def log_info(msg: str):
log.info(msg)
console.print(f"[cyan]ℹ {msg}[/cyan]")
def log_notice(msg: str):
log.info(f"NOTICE: {msg}")
console.print(f"[bold green]✔ {msg}[/bold green]")
def log_warn(msg: str):
log.warning(msg)
console.print(f"[yellow]⚠ {msg}[/yellow]")
def log_error(msg: str):
log.error(msg)
console.print(f"[bold red]❌ {msg}[/bold red]")
def error_exit(msg: str):
log_error(msg)
sys.exit(1)
# ─────────────────────────────────────────────
# !! CONFIGURABLE NETWORK CONSTANTS !!
# Change VAULT_PORT here to redirect all network
# access to a different port without editing
# any other part of the script.
# ─────────────────────────────────────────────
VAULT_HOST = "hpcsangrah-test.pune.cdac.in"
VAULT_PORT = 443 # ← change port here (e.g. 443 for HTTPS, 8080, etc.)
VAULT_PATH = "/vault/OpenCHAI/hpcsuite_registry/"
# Derive the full base URL from the components above.
# Port 80 → http://… (no explicit port in URL for cleanliness)
# Port 443 → https://… (no explicit port in URL for cleanliness)
# Any other port → http://…:<port> (explicit port always shown)
def _build_vault_url(host: str, port: int, path: str) -> str:
if port == 443:
scheme = "https"
portstr = ""
elif port == 80:
scheme = "http"
portstr = ""
else:
scheme = "http"
portstr = f":{port}"
return f"{scheme}://{host}{portstr}{path}"
OPENCHAI_VAULT_URL: str = _build_vault_url(VAULT_HOST, VAULT_PORT, VAULT_PATH)
# ─────────────────────────────────────────────
# Vault credentials dataclass
# ─────────────────────────────────────────────
@dataclass
class VaultCredentials:
username: str
password: str
def auth_header(self) -> str:
"""Return a Basic-Auth Authorization header value."""
token = base64.b64encode(
f"{self.username}:{self.password}".encode("utf-8")
).decode("ascii")
return f"Basic {token}"
@dataclass
class DownloadTask:
tool: str
version: str
filename: str
size: str
url: str
destination: Path
status: str = "PENDING"
detail: str = ""
# ─────────────────────────────────────────────
# HTML href parser (replaces grep/sed pipeline)
# ─────────────────────────────────────────────
class _HrefParser(HTMLParser):
ARCHIVE_EXT = (".tar.gz", ".tgz", ".tar.xz", ".tar", ".img")
def __init__(self):
super().__init__()
self.links: List[str] = []
def handle_starttag(self, tag, attrs):
if tag == "a":
for name, val in attrs:
if name == "href" and val and any(val.endswith(e) for e in self.ARCHIVE_EXT):
self.links.append(val)
def _fetch_url(
url: str,
no_cert: bool = False,
creds: Optional[VaultCredentials] = None,
) -> bytes:
ctx = ssl.create_default_context()
if no_cert:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
headers = {"User-Agent": "openchai-setup/1.0"}
if creds:
headers["Authorization"] = creds.auth_header()
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, context=ctx, timeout=30) as resp:
return resp.read()
def _list_remote_archives(
url: str,
no_cert: bool,
creds: Optional[VaultCredentials] = None,
) -> List[str]:
try:
html = _fetch_url(url, no_cert, creds).decode("utf-8", errors="replace")
parser = _HrefParser()
parser.feed(html)
return parser.links
except Exception as exc:
log_warn(f"Could not fetch archive list from {url}: {exc}")
return []
# ─────────────────────────────────────────────
# Utility helpers
# ─────────────────────────────────────────────
def strip_tar_ext(filename: str) -> str:
for ext in (".tar.gz", ".tgz", ".tar.xz", ".tar"):
if filename.endswith(ext):
return filename[: -len(ext)]
return filename
def _run(cmd: List[str], check: bool = True) -> subprocess.CompletedProcess:
log.debug("RUN: %s", " ".join(cmd))
return subprocess.run(cmd, check=check, text=True)
def _get_available_gb(path: Path) -> Optional[int]:
try:
stat = shutil.disk_usage(path)
return int(stat.free / (1024 ** 3))
except Exception:
return None
def _detect_pkg_manager() -> Optional[str]:
for mgr in ("dnf", "yum"):
if shutil.which(mgr):
return mgr
return None
def _ensure_ansible():
if shutil.which("ansible"):
log_notice("Ansible is already installed.")
return
log_warn("Ansible not found. Installing...")
mgr = _detect_pkg_manager()
if not mgr:
error_exit("No supported package manager (dnf/yum) found.")
try:
_run(["sudo", mgr, "-y", "install", "epel-release"], check=False)
_run(["sudo", mgr, "-y", "install", "ansible-core", "ansible"])
log_notice("Ansible installed successfully.")
except subprocess.CalledProcessError:
error_exit("Failed to install Ansible.")
# ─────────────────────────────────────────────
# OS Detection
# ─────────────────────────────────────────────
def detect_os() -> Tuple[str, str, str]:
"""Returns (os_name, version_id, detected_label)."""
os_release = Path("/etc/os-release")
if not os_release.exists():
error_exit("/etc/os-release missing. Cannot detect OS.")
name, ver = "Unknown", "Unknown"
for line in os_release.read_text().splitlines():
if line.startswith("NAME="):
name = line.split("=", 1)[1].strip().strip('"')
elif line.startswith("VERSION_ID="):
ver = line.split("=", 1)[1].strip().strip('"')
label_map = {
"AlmaLinux": f"alma{ver}",
"Rocky": f"rocky{ver}",
"CentOS": f"centos{ver}",
"Red Hat": f"rhel{ver}",
}
label = next((v for k, v in label_map.items() if k.lower() in name.lower()), "unknown")
return name, ver, label
# ─────────────────────────────────────────────
# Banner
# ─────────────────────────────────────────────
def print_banner():
console.print()
console.print(Panel.fit(
Text.from_markup(
"[bold cyan]OpenCHAI Manager – Cluster Configuration Wizard[/bold cyan]\n"
"[dim]HPC-AI Suite | CDAC Pune[/dim]"
),
box=box.DOUBLE_EDGE,
border_style="cyan",
padding=(1, 4),
))
console.print()
# ─────────────────────────────────────────────
# Section 1 – License
# ─────────────────────────────────────────────
def check_license():
console.print(Rule("[bold]License Agreement[/bold]"))
console.print(
"[yellow]You must read and accept the OpenCHAI Software License Agreement "
"before proceeding.[/yellow]\n"
)
accepted = Confirm.ask("Have you read and accepted the Software License Agreement?", default=False)
if not accepted:
console.print("[red]Installation aborted. License Agreement must be accepted.[/red]")
sys.exit(1)
log.info("License accepted by user.")
# ─────────────────────────────────────────────
# Section 2 – Base Directory
# ─────────────────────────────────────────────
def select_base_dir() -> Path:
console.print(Rule("[bold]Base Directory Selection[/bold]"))
default = SCRIPT_DIR
log_info(f"Default base directory: {default}")
avail_gb = _get_available_gb(default)
if avail_gb is None:
log_warn("Unable to detect disk space. Proceeding with manual entry.")
return _prompt_base_dir()
if avail_gb >= 50:
log_info(f"✅ {default} has sufficient free space ({avail_gb} GB available).")
if Confirm.ask(f"Use default base directory [cyan]{default}[/cyan]?", default=True):
return default
return _prompt_base_dir()
else:
log_warn(f"{default} has insufficient space ({avail_gb} GB < 50 GB required).")
_show_mount_points()
return _prompt_base_dir()
def _show_mount_points():
console.print("\n[cyan]Mount points with ≥ 50 GB free:[/cyan]")
table = Table(box=box.SIMPLE_HEAVY, show_header=True, header_style="bold magenta")
table.add_column("Path", style="white")
table.add_column("Available", style="green", justify="right")
try:
result = subprocess.run(
["df", "-h", "--output=target,avail"], capture_output=True, text=True
)
for line in result.stdout.splitlines()[1:]:
parts = line.split()
if len(parts) >= 2:
size_str = parts[1].rstrip("G")
try:
if float(size_str) >= 50:
table.add_row(parts[0], parts[1])
except ValueError:
pass
except Exception:
pass
console.print(table)
console.print()
def _prompt_base_dir() -> Path:
while True:
raw = Prompt.ask("Enter absolute path for OpenCHAI installation").strip()
p = Path(raw)
if not p.is_absolute():
console.print("[red]Please enter an absolute path.[/red]")
continue
if not p.exists():
if Confirm.ask(f"Directory [cyan]{p}[/cyan] does not exist. Create it?", default=True):
p.mkdir(parents=True, exist_ok=True)
return p
else:
return p
# ─────────────────────────────────────────────
# Section 3 – OS / Arch Parameters
# ─────────────────────────────────────────────
def collect_system_params(detected_os_label: str) -> dict:
console.print(Rule("[bold]System Parameters[/bold]"))
console.print("[dim]Press ENTER to accept detected defaults.[/dim]\n")
os_release = Path("/etc/os-release")
ver_num = ""
for line in os_release.read_text().splitlines():
if line.startswith("VERSION_ID="):
ver_num = line.split("=", 1)[1].strip().strip('"').split(".")[0]
break
defaults = {
"os_arch": platform.machine(),
"os_version": detected_os_label,
"rhel_label": f"rh{ver_num}",
"el_label": f"el{ver_num}",
"kernel": platform.release(),
}
params = {}
fields = [
("os_arch", "OS Architecture"),
("os_version", "OS Version"),
("rhel_label", "RHEL Label"),
("el_label", "Enterprise EL Label"),
("kernel", "Kernel Version"),
]
for key, label in fields:
val = Prompt.ask(f" {label}", default=defaults[key]).strip() or defaults[key]
params[key] = val
# Strip last segment from kernel (e.g. .x86_64)
params["kernel"] = ".".join(params["kernel"].split(".")[:-1]) if "." in params["kernel"] else params["kernel"]
console.print()
return params
# ─────────────────────────────────────────────
# Section 4 – SSL Check Option
# ─────────────────────────────────────────────
def ask_ssl_option() -> bool:
console.print(Rule("[bold]SSL / Host Key Checking[/bold]"))
no_cert = Confirm.ask(
"Disable SSL/host-key checking for downloads? (not recommended for production)",
default=False,
)
if no_cert:
log_warn("SSL/host-key checking disabled for this session.")
return no_cert
# ─────────────────────────────────────────────
# Section 4b – Vault Authentication Credentials
# ─────────────────────────────────────────────
def collect_vault_credentials() -> Optional[VaultCredentials]:
"""
Prompt the user for HTTP Basic-Auth credentials needed to access
the OpenCHAI vault at VAULT_HOST:VAULT_PORT.
Returns a VaultCredentials instance, or None if the user opts out
(e.g. the server does not require authentication).
"""
console.print(Rule("[bold]Vault Registry Authentication[/bold]"))
console.print(
f"[cyan]Registry URL :[/cyan] [white]{OPENCHAI_VAULT_URL}[/white]\n"
f"[cyan]Host :[/cyan] [white]{VAULT_HOST}[/white]\n"
f"[cyan]Port :[/cyan] [white]{VAULT_PORT}[/white]\n"
)
needs_auth = Confirm.ask(
"Does the registry server require authentication?",
default=True,
)
if not needs_auth:
log_notice("Skipping authentication – anonymous access assumed.")
return None
username = ""
while not username:
username = Prompt.ask(" Vault username").strip()
if not username:
console.print("[red]Username cannot be empty.[/red]")
console.print(" Vault password: ", end="")
password = ""
while not password:
try:
password = getpass.getpass(prompt="")
except Exception:
password = Prompt.ask(
" Vault password",
password=True
)
if not password:
console.print(
"[red]Password cannot be empty. Try again.[/red]"
)
console.print(" Vault password: ", end="")
creds = VaultCredentials(
username=username,
password=password
)
log.info(
"Vault credentials collected for user: %s",
username
)
log_notice(
f"Credentials stored for user '{username}' "
f"(password redacted from log)."
)
return creds
# ─────────────────────────────────────────────
# Registry Tar Handling
# ─────────────────────────────────────────────
TAR_EXTS = (".tar.gz", ".tgz", ".tar.xz", ".tar")
def _find_local_tars(directory: Path) -> List[Path]:
if not directory.exists():
return []
return [
f for f in directory.iterdir()
if f.is_file()
and any(f.name.endswith(e) for e in TAR_EXTS)
]
def _safe_extract_tar(tf: tarfile.TarFile, path: Path):
"""
Secure tar extraction preventing path traversal attacks.
"""
abs_path = path.resolve()
for member in tf.getmembers():
member_path = (path / member.name).resolve()
if not str(member_path).startswith(str(abs_path)):
raise Exception(
f"Blocked suspicious tar path: {member.name}"
)
tf.extractall(path)
def _extract_tar(
src,
dest_dir: Path,
is_stream: bool = False
) -> bool:
"""Extract tar from file path or file-like stream into dest_dir."""
dest_dir.mkdir(parents=True, exist_ok=True)
try:
with Progress(
SpinnerColumn(),
TextColumn(
"[progress.description]{task.description}"
),
console=console,
) as progress:
task = progress.add_task(
"Extracting archive…",
total=None
)
if is_stream:
with tarfile.open(
fileobj=src,
mode="r|*"
) as tf:
_safe_extract_tar(tf, dest_dir)
else:
with tarfile.open(
src,
mode="r:*"
) as tf:
_safe_extract_tar(tf, dest_dir)
progress.update(task, completed=True)
return True
except Exception as exc:
log_warn(f"Extraction failed: {exc}")
return False
def _show_download_queue(tasks: List[DownloadTask]):
console.print(
Rule("[bold]Download Queue[/bold]")
)
table = Table(
box=box.ROUNDED,
header_style="bold cyan"
)
table.add_column("#", justify="center")
table.add_column("Tool")
table.add_column("Version")
table.add_column("Image")
table.add_column("Size", justify="right")
table.add_column("Destination")
for idx, task in enumerate(tasks, 1):
table.add_row(
str(idx),
task.tool,
task.version,
task.filename,
task.size,
str(task.destination)
)
console.print(table)
console.print(
f"\n[bold]{len(tasks)}[/bold] image(s) queued"
)
def _show_download_report(tasks: List[DownloadTask]):
console.print(
Rule("[bold]Download Report[/bold]")
)
table = Table(
box=box.SIMPLE_HEAVY
)
table.add_column("Status")
table.add_column("Tool")
table.add_column("Image")
table.add_column("Detail")
for task in tasks:
status_icon = {
"DONE": "✔",
"SKIP": "⏭",
"FAILED": "❌"
}.get(task.status, "?")
table.add_row(
status_icon,
task.tool,
task.filename,
task.detail
)
console.print(table)
def _download_and_extract(
task: DownloadTask,
no_cert: bool,
creds: Optional[VaultCredentials] = None,
) -> bool:
ctx = ssl.create_default_context()
if no_cert:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
headers = {
"User-Agent": "openchai-setup/1.0"
}
if creds:
headers["Authorization"] = creds.auth_header()
tmp_tar = (
task.destination.parent /
f"{task.filename}.download"
)
try:
req = urllib.request.Request(
task.url,
headers=headers
)
with urllib.request.urlopen(
req,
context=ctx,
timeout=300
) as resp:
total = int(
resp.headers.get(
"Content-Length",
0
)
)
with Progress(
SpinnerColumn(),
TextColumn(
"[progress.description]{task.description}"
),
BarColumn(),
DownloadColumn(),
TransferSpeedColumn(),
TimeRemainingColumn(),
console=console,
) as progress:
dl_task = progress.add_task(
f"Downloading {task.filename}",
total=total
)
with open(tmp_tar, "wb") as out:
while True:
chunk = resp.read(1024 * 1024)
if not chunk:
break
out.write(chunk)
progress.update(
dl_task,
advance=len(chunk)
)
log_notice(
f"Download completed: "
f"{task.filename}"
)
if not _extract_tar(
str(tmp_tar),
task.destination.parent
):
task.status = "FAILED"
task.detail = "Extraction failed"
return False
task.status = "DONE"
task.detail = "Downloaded & extracted"
return True
except Exception as exc:
task.status = "FAILED"
task.detail = str(exc)
log_warn(
f"Download failed: {exc}"
)
return False
finally:
try:
if tmp_tar.exists():
tmp_tar.unlink()
except Exception:
pass
# ─────────────────────────────────────────────
# Main Registry Handler
# ─────────────────────────────────────────────
def handle_registry_tar(
base_dir: Path,
arch: str,
os_version: str,
no_cert: bool,
creds: Optional[VaultCredentials] = None,
) -> str:
console.print(
Rule("[bold]Host Machine Registry (Tar)[/bold]")
)
registry_dir = (
base_dir /
"hpcsuite_registry" /
"hostmachine_reg" /
arch
)
version_dir = registry_dir / os_version
version_dir.mkdir(
parents=True,
exist_ok=True
)
network_url = (
f"{OPENCHAI_VAULT_URL}"
f"hostmachine_reg/"
f"{arch}/"
f"{os_version}/"
)
local_tars = _find_local_tars(version_dir)
# ─────────────────────────────────────────
# LOCAL TAR FILES
# ─────────────────────────────────────────
if local_tars:
log_info(
f"Found {len(local_tars)} local tar file(s)"
)
table = Table(
box=box.ROUNDED,
header_style="bold cyan"
)
table.add_column("#", justify="center")
table.add_column("Tarball")
table.add_column("Location")
for idx, tar in enumerate(local_tars, 1):
table.add_row(
str(idx),
tar.name,
str(tar.parent)
)
console.print(table)
raw = Prompt.ask(
"Select local tarball",
default="1"
)
try:
idx = int(raw) - 1
except Exception:
log_warn("Invalid selection")
return "__SET_LATER__"
if idx < 0 or idx >= len(local_tars):
log_warn("Invalid selection")
return "__SET_LATER__"
chosen = local_tars[idx]
openchai_version = strip_tar_ext(
chosen.name
)
extracted_dir = (
version_dir / openchai_version
)
# Already extracted
if extracted_dir.exists() and any(extracted_dir.iterdir()):
log_notice(
f"Already complete, skipping: "
f"{openchai_version}"
)
return openchai_version
log_info(
f"Extracting {chosen.name}"
)
if _extract_tar(
str(chosen),
version_dir
):
log_notice(
f"Registry extracted successfully: "
f"{openchai_version}"
)
return openchai_version
log_warn(
"Extraction failed."
)
return "__SET_LATER__"
# ─────────────────────────────────────────
# NO LOCAL TARS
# ─────────────────────────────────────────
log_warn(
f"No tar files found in {version_dir}"
)
console.print("\n [bold]Options:[/bold]")
console.print(" [cyan]1[/cyan] Download from network")
console.print(" [cyan]2[/cyan] Install manually later")
console.print(" [cyan]3[/cyan] Skip")
choice = Prompt.ask(
"Select option",
choices=["1", "2", "3"],
default="3"
)
if choice == "2":
log_warn(
f"Place registry tar later in:\n"
f" → {version_dir}"
)
return "__SET_MANUALLY__"
if choice == "3":
return "__SET_LATER__"
# ─────────────────────────────────────────
# FETCH REMOTE FILES
# ─────────────────────────────────────────
log_info(
f"Fetching tar list from {network_url} …"
)
remote_files = _list_remote_archives(
network_url,
no_cert,
creds
)
if not remote_files:
log_warn(
"No archives found on network."
)
return "__SET_LATER__"
# ─────────────────────────────────────────
# REMOTE TABLE
# ─────────────────────────────────────────
table = Table(
title="Available OpenCHAI Packages",
box=box.ROUNDED,
header_style="bold cyan"
)
table.add_column("#", justify="center")
table.add_column("Package")
table.add_column("Version")
table.add_column("Tarball")
for idx, file in enumerate(remote_files, 1):
version = strip_tar_ext(file)
table.add_row(
str(idx),
"openchai",
version,
file
)
console.print(table)
raw = Prompt.ask(
"Select file to download",
default="1"
)
try:
idx = int(raw) - 1
except Exception:
log_warn("Invalid selection")
return "__SET_LATER__"
if idx < 0 or idx >= len(remote_files):
log_warn("Invalid selection")
return "__SET_LATER__"
selected = remote_files[idx]
openchai_version = strip_tar_ext(
Path(selected).name
)