-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate
More file actions
executable file
·1799 lines (1542 loc) · 64.6 KB
/
create
File metadata and controls
executable file
·1799 lines (1542 loc) · 64.6 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
"""
Interactive TUI for creating Kubernetes resources (PVCs, Deployments, TrainJobs, interactive sessions).
Run with: uv run ./hydra
"""
import argparse
import json
import os
import re
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import Optional
try:
from textual.app import App, ComposeResult
from textual.containers import Container, Horizontal, Vertical
from textual.widgets import (
Button,
Header,
Footer,
Label,
Input,
Select,
RadioSet,
RadioButton,
Checkbox,
Static,
TextArea,
ListView,
ListItem,
)
from textual.screen import Screen
from textual.reactive import reactive
from rich.syntax import Syntax
from rich.panel import Panel
from rich.text import Text
except ImportError:
print("Error: Required dependencies not found.")
print("Install with: pip install textual rich")
sys.exit(1)
class Spacer(Static):
"""Reusable vertical spacer component."""
def __init__(self, height: int = 1):
super().__init__("", classes=f"spacer-{height}")
self.styles.height = height
# Configuration
DOTFILE_NAME = ".new-config"
SCRIPT_DIR = Path(__file__).parent.resolve()
LAUNCH_D = SCRIPT_DIR / "launch.d"
TEMPLATES_DIR = LAUNCH_D / "templates"
PROFILES_DIR = LAUNCH_D / "instance_types"
GENERIC_CONFIG = LAUNCH_D / "generic.yaml"
# Cluster context (global - can be changed at runtime)
KUBE_CONTEXT: str = os.environ.get("KUBE_CONTEXT", "")
def get_current_context() -> str:
"""Get current kubectl context name."""
global KUBE_CONTEXT
if KUBE_CONTEXT:
return KUBE_CONTEXT
result = subprocess.run(
["kubectl", "config", "current-context"],
capture_output=True, text=True
)
if result.returncode == 0:
return result.stdout.strip()
return "(unknown)"
def get_contexts() -> list[str]:
"""Fetch available kubectl contexts."""
result = subprocess.run(
["kubectl", "config", "get-contexts", "-o", "name"],
capture_output=True, text=True
)
if result.returncode != 0:
return []
return [ctx.strip() for ctx in result.stdout.strip().split("\n") if ctx.strip()]
def set_context(context: str) -> bool:
"""Set the kubectl context (updates global)."""
global KUBE_CONTEXT
# Verify context exists
contexts = get_contexts()
if context not in contexts and context != "":
return False
KUBE_CONTEXT = context
return True
def run_kubectl(args: list[str], capture_output: bool = True) -> tuple[int, str, str]:
"""Run kubectl command and return (returncode, stdout, stderr)."""
cmd = ["kubectl"]
if KUBE_CONTEXT:
cmd.extend(["--context", KUBE_CONTEXT])
cmd.extend(args)
result = subprocess.run(cmd, capture_output=capture_output, text=True)
return result.returncode, result.stdout, result.stderr
def get_namespaces() -> list[str]:
"""Fetch available namespaces from kubectl."""
rc, stdout, _ = run_kubectl(["get", "namespaces", "-o", "json"])
if rc != 0:
return []
try:
data = json.loads(stdout)
return [item["metadata"]["name"] for item in data.get("items", [])]
except (json.JSONDecodeError, KeyError):
return []
def get_pvcs(namespace: str) -> list[dict]:
"""Fetch PVCs from the specified namespace."""
rc, stdout, _ = run_kubectl(["get", "pvc", "-n", namespace, "-o", "json"])
if rc != 0:
return []
try:
data = json.loads(stdout)
pvcs = []
for item in data.get("items", []):
pvcs.append({
"name": item["metadata"]["name"],
"storage": item["spec"].get("resources", {}).get("requests", {}).get("storage", "?"),
"access_modes": item["spec"].get("accessModes", []),
"status": item["status"].get("phase", "?"),
})
return pvcs
except (json.JSONDecodeError, KeyError):
return []
def get_storage_classes() -> list[tuple[str, str]]:
"""Fetch available storage classes from kubectl."""
rc, stdout, _ = run_kubectl(["get", "sc", "-o", "json"])
if rc != 0:
return []
try:
data = json.loads(stdout)
storage_classes = []
for item in data.get("items", []):
name = item["metadata"]["name"]
provisioner = item.get("provisioner", "unknown")
is_default = "(default)" if item.get("metadata", {}).get("annotations", {}).get("storageclass.kubernetes.io/is-default-class") == "true" else ""
display = f"{name} - {provisioner} {is_default}".strip()
storage_classes.append((display, name))
return storage_classes
except (json.JSONDecodeError, KeyError):
return []
def load_dotfile() -> dict:
"""Load saved configuration from dotfile."""
dotfile = SCRIPT_DIR / DOTFILE_NAME
if dotfile.exists():
try:
with open(dotfile) as f:
return json.load(f)
except (json.JSONDecodeError, IOError):
pass
return {}
def save_dotfile(config: dict) -> None:
"""Save configuration to dotfile."""
dotfile = SCRIPT_DIR / DOTFILE_NAME
try:
with open(dotfile, "w") as f:
json.dump(config, f, indent=2)
except IOError as e:
print(f"Warning: Could not save config: {e}")
def yaml_value(file_path: Path, key: str) -> Optional[str]:
"""Simple YAML value extraction."""
if not file_path.exists():
return None
with open(file_path) as f:
for line in f:
line = line.strip()
if line.startswith(f"{key}:"):
return line.split(":", 1)[1].strip()
return None
def get_profiles() -> list[tuple[str, str]]:
"""Get available instance type profiles."""
profiles = []
if PROFILES_DIR.exists():
for f in sorted(PROFILES_DIR.glob("*.yaml")):
name = f.stem
desc = yaml_value(f, "description") or "No description"
profiles.append((name, desc))
return profiles
def get_nodetiers() -> list[tuple[str, str, dict]]:
"""Get node tiers from cluster with their resource profiles.
Returns list of (display_name, tier_name, resources_dict).
"""
# First try to get from cluster node labels
rc, stdout, _ = run_kubectl(["get", "nodes", "-o", "json"])
tiers = {}
if rc == 0:
try:
data = json.loads(stdout)
for node in data.get("items", []):
labels = node.get("metadata", {}).get("labels", {})
tier = labels.get("node-tier", "")
if tier:
# Get allocatable resources
allocatable = node.get("status", {}).get("allocatable", {})
if tier not in tiers:
tiers[tier] = {
"count": 0,
"cpus": [],
"memory": [],
"gpus": [],
}
tiers[tier]["count"] += 1
tiers[tier]["cpus"].append(allocatable.get("cpu", "0"))
tiers[tier]["memory"].append(allocatable.get("memory", "0"))
tiers[tier]["gpus"].append(allocatable.get("nvidia.com/gpu", "0"))
except (json.JSONDecodeError, KeyError):
pass
result = []
# Add "none" option for CPU-only workloads
result.append((
"none (CPU only - no GPU)",
"none",
{"cpu_request": "1", "cpu_limit": "4", "mem_request": "4Gi", "mem_limit": "16Gi", "gpu_request": "0", "gpu_limit": "0"}
))
# Add discovered tiers from cluster
for tier, info in sorted(tiers.items()):
# Use max resources as limits
max_cpu = max([int(c.replace("m", "")) // 1000 if "m" in c else int(c) for c in info["cpus"]]) if info["cpus"] else 4
max_mem = max([int(m.replace("Ki", "")) // (1024*1024) if "Ki" in m else int(m.replace("Gi", "").replace("Mi", "") // 1024 if "Mi" in m else int(m)) for m in info["memory"]]) if info["memory"] else 16
has_gpu = any(int(g) > 0 for g in info["gpus"] if g.isdigit())
display = f"{tier} ({info['count']} nodes, ~{max_cpu} CPU, ~{max_mem}Gi RAM"
if has_gpu:
max_gpu = max([int(g) for g in info["gpus"] if g.isdigit()])
display += f", up to {max_gpu} GPU"
display += ")"
resources = {
"cpu_request": str(max_cpu // 2),
"cpu_limit": str(max_cpu),
"mem_request": f"{max_mem // 2}Gi",
"mem_limit": f"{max_mem}Gi",
"gpu_request": "1" if has_gpu else "0",
"gpu_limit": str(max([int(g) for g in info["gpus"] if g.isdigit()])) if has_gpu else "0",
}
result.append((display, tier, resources))
# Fallback: if no tiers discovered, add some defaults from profiles
if len(result) <= 1:
for profile_name, desc in get_profiles():
profile_path = PROFILES_DIR / f"{profile_name}.yaml"
tier = yaml_value(profile_path, "nodetier")
if tier and tier not in [t[1] for t in result]:
resources = {
"cpu_request": yaml_value(profile_path, "cpu_request") or "2",
"cpu_limit": yaml_value(profile_path, "cpu_limit") or "4",
"mem_request": yaml_value(profile_path, "memory_request") or "8Gi",
"mem_limit": yaml_value(profile_path, "memory_limit") or "16Gi",
"gpu_request": yaml_value(profile_path, "gpu_request") or "0",
"gpu_limit": yaml_value(profile_path, "gpu_limit") or "0",
}
result.append((f"{tier} (from {profile_name} profile)", tier, resources))
return result
def get_default_config() -> dict:
"""Load default values from generic.yaml."""
defaults = {
"namespace": "default",
"image": "ubuntu:22.04",
"data_pvc": "data",
"checkpoint_pvc": "checkpoints",
"s3_data_pvc": "s3-data",
"service_account_name": "default",
}
if GENERIC_CONFIG.exists():
for key in defaults:
val = yaml_value(GENERIC_CONFIG, key)
if val:
defaults[key] = val
return defaults
class NamespaceScreen(Screen):
"""Screen for selecting namespace on first run."""
BINDINGS = [("q", "exit", "Quit"), ("enter", "select", "Select")]
def action_exit(self):
self.app.exit()
def __init__(self):
self.namespaces = get_namespaces()
self.selected_namespace = None
super().__init__()
def compose(self) -> ComposeResult:
yield Header(show_clock=True)
yield Container(
Label("Select Kubernetes Namespace", classes="title"),
Label("This will be saved and used as the default for future runs."),
ListView(
*[ListItem(Label(f" {ns}"), id=f"ns-{ns}") for ns in self.namespaces] if self.namespaces else [ListItem(Label(" (no namespaces found - check kubectl connection)"), id="ns-none")],
id="namespace-list"
),
Input(placeholder="Or type a namespace manually...", id="manual-namespace"),
Horizontal(
Button("Save & Continue", variant="primary", id="save-btn"),
Button("Quit", variant="error", id="quit-btn"),
),
id="namespace-container"
)
yield Footer()
def on_mount(self):
if self.namespaces:
self.query_one("#namespace-list", ListView).index = 0
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "quit-btn":
self.app.exit()
elif event.button.id == "save-btn":
manual = self.query_one("#manual-namespace", Input).value
list_view = self.query_one("#namespace-list", ListView)
if manual.strip():
self.selected_namespace = manual.strip()
elif list_view.highlighted_child and self.namespaces:
# Get namespace by index
idx = list_view.index
if 0 <= idx < len(self.namespaces):
self.selected_namespace = self.namespaces[idx]
if self.selected_namespace:
self.dismiss(self.selected_namespace)
def action_select(self):
self.on_button_pressed(Button.Pressed(self.query_one("#save-btn")))
class ContextScreen(Screen):
"""Screen for selecting kubectl context."""
BINDINGS = [("q", "exit", "Quit"), ("enter", "select", "Select")]
def action_exit(self):
self.app.exit()
def __init__(self):
self.contexts = get_contexts()
self.selected_context = None
super().__init__()
def _safe_id(self, ctx: str) -> str:
"""Create a safe widget ID from context name."""
# Replace invalid chars with underscore
safe = "".join(c if c.isalnum() or c in "-_" else "_" for c in ctx)
# Ensure doesn't start with number
if safe and safe[0].isdigit():
safe = "ctx_" + safe
return f"ctx-{safe}"
def compose(self) -> ComposeResult:
current = get_current_context()
yield Header(show_clock=True)
yield Container(
Label("Select Kubernetes Context", classes="title"),
Label(f"Current: {current}"),
Label("Select a context (or press Enter to use current):"),
ListView(
*[ListItem(Label(f" {ctx}"), id=self._safe_id(ctx)) for ctx in self.contexts] if self.contexts else [ListItem(Label(" (no contexts found - check kubectl config)"), id="ctx-none")],
id="context-list"
),
Horizontal(
Button("Save & Continue", variant="primary", id="save-btn"),
Button("Quit", variant="error", id="quit-btn"),
),
id="context-container"
)
yield Footer()
def on_mount(self):
# Highlight current context if in list
current = get_current_context()
if self.contexts and current in self.contexts:
idx = self.contexts.index(current)
self.query_one("#context-list", ListView).index = idx
elif self.contexts:
self.query_one("#context-list", ListView).index = 0
def _index_to_context(self, idx: int) -> str | None:
"""Map list index back to original context name."""
if 0 <= idx < len(self.contexts):
return self.contexts[idx]
return None
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "quit-btn":
self.app.exit()
elif event.button.id == "save-btn":
list_view = self.query_one("#context-list", ListView)
if list_view.highlighted_child and self.contexts:
# Map index to original context name
self.selected_context = self._index_to_context(list_view.index)
else:
# Use current context (empty string means use current)
self.selected_context = ""
self.dismiss(self.selected_context)
def action_select(self):
self.on_button_pressed(Button.Pressed(self.query_one("#save-btn")))
class MainMenuScreen(Screen):
"""Main menu screen."""
BINDINGS = [
("q", "exit", "Quit"),
("1", "new_pvc", "New PVC"),
("2", "new_deployment", "New Deployment/TrainJob"),
("3", "interactive", "Interactive Session"),
("n", "change_namespace", "Change Namespace"),
("c", "change_context", "Change Context"),
]
def action_exit(self):
self.app.exit()
namespace = reactive("default")
def __init__(self, namespace: str = "default"):
self.start_namespace = namespace
super().__init__()
def compose(self) -> ComposeResult:
cluster = get_current_context()
yield Header(show_clock=True)
yield Container(
Label("Kubernetes Resource Creator", classes="title"),
Label(f"Cluster: [bold]{cluster}[/bold] | Namespace: [bold]{self.start_namespace}[/bold]", id="ns-label"),
Spacer(),
Label("Select an action:", classes="section-label"),
Horizontal(
Button("1. New PVC", id="btn-pvc", variant="primary"),
Button("2. New Deployment/TrainJob", id="btn-deploy", variant="primary"),
Button("3. Interactive Session", id="btn-interactive", variant="primary"),
),
Spacer(),
Horizontal(
Button("Change Context", id="btn-ctx", variant="default"),
Button("Change Namespace", id="btn-ns", variant="default"),
Button("Quit", id="btn-quit", variant="error"),
),
id="main-container"
)
yield Footer()
def on_mount(self):
self.namespace = self.start_namespace
self.update_ns_label()
def watch_namespace(self):
self.update_ns_label()
def update_ns_label(self):
label = self.query_one("#ns-label", Label)
cluster = get_current_context()
label.update(f"Cluster: [bold]{cluster}[/bold] | Namespace: [bold]{self.namespace}[/bold]")
def on_button_pressed(self, event: Button.Pressed) -> None:
btn_id = event.button.id
if btn_id == "btn-quit":
self.app.exit()
elif btn_id == "btn-pvc":
self.action_new_pvc()
elif btn_id == "btn-deploy":
self.action_new_deployment()
elif btn_id == "btn-interactive":
self.action_interactive()
elif btn_id == "btn-ns":
self.action_change_namespace()
elif btn_id == "btn-ctx":
self.action_change_context()
def action_change_context(self):
def on_context_change(new_ctx: str | None):
if new_ctx is not None:
set_context(new_ctx)
self.update_ns_label()
save_dotfile({"namespace": self.namespace, "context": new_ctx})
self.notify(f"Context changed to: {new_ctx or '(current)'}")
self.app.push_screen(ContextScreen(), callback=on_context_change)
def action_new_pvc(self):
self.app.push_screen(PVCScreen(self.namespace))
def action_new_deployment(self):
self.app.push_screen(DeploymentScreen(self.namespace))
def action_interactive(self):
self.app.push_screen(InteractiveScreen(self.namespace))
def action_change_namespace(self):
def on_namespace_change(new_ns: str | None):
if new_ns:
self.namespace = new_ns
save_dotfile({"namespace": new_ns, "context": KUBE_CONTEXT})
self.notify(f"Namespace changed to: {new_ns}")
self.app.push_screen(NamespaceScreen(), callback=on_namespace_change)
class PVCScreen(Screen):
"""Screen for creating a new PVC."""
BINDINGS = [("q", "back", "Back"), ("escape", "back", "Back")]
def __init__(self, namespace: str):
self.namespace = namespace
self.storage_classes = []
super().__init__()
def compose(self) -> ComposeResult:
yield Header(show_clock=True)
yield Container(
Label(f"New PVC (namespace: {self.namespace})", classes="title"),
Label("PVC Name:"),
Input(placeholder="my-data-pvc", id="pvc-name"),
Label("Storage Size:"),
Input(placeholder="10Gi", value="10Gi", id="pvc-size"),
Label("Access Mode:"),
Select(
[
("ReadWriteOnce (RWO) - Single node read/write", "ReadWriteOnce"),
("ReadWriteMany (RWX) - Multiple nodes read/write", "ReadWriteMany"),
("ReadOnlyMany (ROX) - Multiple nodes read-only", "ReadOnlyMany"),
],
value="ReadWriteOnce",
id="pvc-access"
),
Label("Storage Class:"),
Select(
[("Loading...", "")],
value="",
id="pvc-storage-class"
),
Label("Output configuration to:"),
Input(placeholder="./pvc-manifests", value=".", id="pvc-folder"),
Spacer(),
Horizontal(
Button("Generate", variant="primary", id="generate-btn"),
Button("Back", variant="default", id="back-btn"),
),
id="pvc-container"
)
yield Footer()
def on_mount(self):
# Load storage classes asynchronously
self.run_worker(self._load_storage_classes())
async def _load_storage_classes(self):
"""Load storage classes in background."""
import asyncio
# Run the blocking kubectl call in a thread
loop = asyncio.get_event_loop()
self.storage_classes = await loop.run_in_executor(None, get_storage_classes)
# Update the select widget
sc_select = self.query_one("#pvc-storage-class", Select)
if self.storage_classes:
# Find default
default_sc = None
for display, name in self.storage_classes:
if "(default)" in display:
default_sc = name
break
if not default_sc:
default_sc = self.storage_classes[0][1]
# Update options
sc_select.set_options([(d, n) for d, n in self.storage_classes])
sc_select.value = default_sc
else:
# Replace with input if no storage classes found
sc_select.set_options([("(none available)", "")])
sc_select.value = ""
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "back-btn":
self.action_back()
elif event.button.id == "generate-btn":
self.generate_pvc()
def generate_pvc(self):
name = self.query_one("#pvc-name", Input).value.strip()
size = self.query_one("#pvc-size", Input).value.strip()
access_mode = self.query_one("#pvc-access", Select).value
folder = self.query_one("#pvc-folder", Input).value.strip()
# Get storage class
storage_class = ""
try:
sc_select = self.query_one("#pvc-storage-class", Select)
storage_class = sc_select.value
except Exception:
try:
sc_manual = self.query_one("#pvc-storage-class-manual", Input)
storage_class = sc_manual.value.strip()
except Exception:
pass
if not name:
self.notify("PVC name is required", severity="error")
return
if not size:
self.notify("Storage size is required", severity="error")
return
# Generate PVC manifest
storage_class_line = f" storageClassName: {storage_class}\n" if storage_class else ""
manifest = f"""apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: {name}
namespace: {self.namespace}
spec:
accessModes:
- {access_mode}
{storage_class_line} resources:
requests:
storage: {size}
"""
# Save to file
folder_path = Path(folder).expanduser().resolve()
folder_path.mkdir(parents=True, exist_ok=True)
output_file = folder_path / f"{name}-pvc.yaml"
try:
with open(output_file, "w") as f:
f.write(manifest)
self.notify(f"PVC manifest saved to: {output_file}")
# Ask if user wants to apply
def apply_callback(apply: bool):
if apply:
rc, _, stderr = run_kubectl(["apply", "-f", str(output_file)])
if rc == 0:
self.notify(f"PVC {name} created successfully")
else:
self.notify(f"Failed to apply PVC: {stderr}", severity="error")
self.action_back()
self.app.push_screen(ConfirmScreen(f"Apply PVC {name} to namespace {self.namespace}?"), callback=apply_callback)
except IOError as e:
self.notify(f"Failed to save manifest: {e}", severity="error")
def action_back(self):
self.app.pop_screen()
class PVCSelectScreen(Screen):
"""Screen for selecting PVCs from the cluster."""
BINDINGS = [("q", "back", "Back"), ("escape", "back", "Back")]
def __init__(self, namespace: str, selected_pvcs: list[str] = None):
self.namespace = namespace
self.pvcs = get_pvcs(namespace)
self.selected_pvcs = selected_pvcs or []
self.result_pvcs = []
super().__init__()
def compose(self) -> ComposeResult:
yield Header(show_clock=True)
yield Container(
Label(f"Select PVCs to mount (namespace: {self.namespace})", classes="title"),
Spacer(),
Label("Available PVCs:") if self.pvcs else Label("No PVCs found in namespace."),
Spacer(),
*self._build_pvc_list(),
Spacer(),
Horizontal(
Button("Confirm Selection", variant="primary", id="confirm-btn"),
Button("Create New PVC First", variant="default", id="new-pvc-btn"),
Button("Back", variant="default", id="back-btn"),
),
id="pvc-select-container"
)
yield Footer()
def _build_pvc_list(self):
widgets = []
for pvc in self.pvcs:
is_checked = pvc["name"] in self.selected_pvcs
widgets.append(
Checkbox(
f"{pvc['name']} ({pvc['storage']}, {', '.join(pvc['access_modes'])}, {pvc['status']})",
value=is_checked,
id=f"pvc-{pvc['name']}"
)
)
return widgets
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "back-btn":
self.dismiss(None)
elif event.button.id == "confirm-btn":
self.confirm_selection()
elif event.button.id == "new-pvc-btn":
self.app.push_screen(PVCScreen(self.namespace))
def confirm_selection(self):
selected = []
for pvc in self.pvcs:
checkbox = self.query_one(f"#pvc-{pvc['name']}", Checkbox)
if checkbox.value:
selected.append(pvc["name"])
self.dismiss(selected)
class DeploymentScreen(Screen):
"""Screen for creating a new Deployment or TrainJob."""
BINDINGS = [("q", "back", "Back"), ("escape", "back", "Back")]
def __init__(self, namespace: str):
self.namespace = namespace
self.defaults = get_default_config()
self.profiles = get_profiles()
self.nodetiers = []
self.selected_pvcs = []
super().__init__()
def compose(self) -> ComposeResult:
yield Header(show_clock=True)
yield Container(
Label(f"New Deployment/TrainJob (namespace: {self.namespace})", classes="title"),
Label("Resource Type:"),
RadioSet(
RadioButton("Deployment", value=True, id="res-deployment"),
RadioButton("TrainJob", id="res-trainjob"),
id="resource-type"
),
Spacer(),
Label("Node Tier (determines resources):"),
Select(
[("Loading...", "none")],
value="none",
id="nodetier"
),
Label("Optional Init Script (bash commands for init container):"),
TextArea(id="init-script", language="bash", text=""),
Label("Container Image:"),
Input(placeholder="e.g., pytorch/pytorch:2.0.0-cuda11.7-cudnn8-runtime", value=self.defaults.get("image", ""), id="image"),
Label("Entrypoint Command (bash):"),
TextArea(id="entrypoint", language="bash", text="#!/bin/bash\nset -euxo pipefail\n\necho 'Hello, World!'\n"),
Label(f"Selected PVCs: {len(self.selected_pvcs)}", id="pvc-label"),
Button("Select PVCs to Mount", id="pvc-btn"),
Spacer(),
Label("Instance Type (for nodepool selection):"),
Select(
[(f"{p[0]} - {p[1]}", p[0]) for p in self.profiles] if self.profiles else [("default", "default")],
value=self.profiles[0][0] if self.profiles else "default",
id="profile"
),
Label("Output configuration to:"),
Input(placeholder="./my-job", value=".", id="output-folder"),
Spacer(),
Horizontal(
Button("Preview & Confirm", variant="primary", id="preview-btn"),
Button("Back", variant="default", id="back-btn"),
),
id="deploy-container"
)
yield Footer()
def on_mount(self):
self.run_worker(self._load_nodetiers())
async def _load_nodetiers(self):
"""Load node tiers in background."""
import asyncio
loop = asyncio.get_event_loop()
self.nodetiers = await loop.run_in_executor(None, get_nodetiers)
# Update the select widget
tier_select = self.query_one("#nodetier", Select)
if self.nodetiers:
# Find default (none first, or first available)
default_tier = "none"
for display, name, resources in self.nodetiers:
if name == "none":
default_tier = "none"
break
if default_tier == "none" and self.nodetiers:
default_tier = self.nodetiers[0][1]
tier_select.set_options([(d, n) for d, n, r in self.nodetiers])
tier_select.value = default_tier
else:
tier_select.set_options([("none (CPU only)", "none")])
tier_select.value = "none"
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "back-btn":
self.action_back()
elif event.button.id == "pvc-btn":
self.select_pvcs()
elif event.button.id == "preview-btn":
self.preview()
def select_pvcs(self):
def on_select(pvcs: list[str] | None):
if pvcs is not None:
self.selected_pvcs = pvcs
label = self.query_one("#pvc-label", Label)
label.update(f"Selected PVCs: {len(self.selected_pvcs)}")
self.app.push_screen(PVCSelectScreen(self.namespace, self.selected_pvcs), callback=on_select)
def preview(self):
# Gather all inputs
resource_type = "Deployment" if self.query_one("#res-deployment", RadioButton).value else "TrainJob"
init_script = self.query_one("#init-script", TextArea).text.strip()
image = self.query_one("#image", Input).value.strip()
entrypoint = self.query_one("#entrypoint", TextArea).text.strip()
profile = self.query_one("#profile", Select).value
nodetier = self.query_one("#nodetier", Select).value
folder = self.query_one("#output-folder", Input).value.strip()
if not image:
self.notify("Container image is required", severity="error")
return
if not entrypoint:
self.notify("Entrypoint command is required", severity="error")
return
if not folder:
self.notify("Output folder is required", severity="error")
return
# Get resources for selected nodetier
nodetier_resources = None
for tier in self.nodetiers:
if tier[1] == nodetier:
nodetier_resources = tier[2]
break
if not nodetier_resources:
nodetier_resources = self.nodetiers[0][2] if self.nodetiers else {
"cpu_request": "1", "cpu_limit": "4", "mem_request": "4Gi", "mem_limit": "16Gi", "gpu_request": "0", "gpu_limit": "0"
}
self.app.push_screen(ConfirmDeploymentScreen(
namespace=self.namespace,
resource_type=resource_type,
init_script=init_script,
image=image,
entrypoint=entrypoint,
profile=profile,
nodetier=nodetier,
nodetier_resources=nodetier_resources,
pvcs=self.selected_pvcs,
folder=folder,
defaults=self.defaults,
))
def action_back(self):
self.app.pop_screen()
class ConfirmDeploymentScreen(Screen):
"""Screen to confirm and apply deployment."""
BINDINGS = [("q", "back", "Back"), ("escape", "back", "Back")]
def __init__(self, namespace: str, resource_type: str, init_script: str, image: str,
entrypoint: str, profile: str, nodetier: str, nodetier_resources: dict,
pvcs: list[str], folder: str, defaults: dict):
self.namespace = namespace
self.resource_type = resource_type
self.init_script = init_script
self.image = image
self.entrypoint = entrypoint
self.profile = profile
self.nodetier = nodetier
self.nodetier_resources = nodetier_resources
self.pvcs = pvcs
self.folder = folder
self.defaults = defaults
super().__init__()
def compose(self) -> ComposeResult:
# Generate preview of what will be created
preview = self._generate_preview()
yield Header(show_clock=True)
yield Container(
Label("Confirm Deployment", classes="title"),
Label("The following will be created:"),
Static(Panel(preview, title="Generated Files")),
Horizontal(
Button("Create & Apply", variant="success", id="apply-btn"),
Button("Back", variant="default", id="back-btn"),
),
id="confirm-container"
)
yield Footer()
def _generate_preview(self) -> str:
folder_path = Path(self.folder).expanduser().resolve()
lines = [
f"Folder: {folder_path}",
f"Files:",
f" - deploy.yaml ({self.resource_type} manifest)",
f" - entrypoint.sh",
]
if self.init_script:
lines.append(" - init.sh")
lines.extend([
"",
f"Configuration:",
f" Namespace: {self.namespace}",
f" Image: {self.image}",
f" Profile: {self.profile}",
f" Node Tier: {self.nodetier}",
f" Resources:",
f" CPU: {self.nodetier_resources.get('cpu_request', '?')}/{self.nodetier_resources.get('cpu_limit', '?')}",
f" Memory: {self.nodetier_resources.get('mem_request', '?')}/{self.nodetier_resources.get('mem_limit', '?')}",
f" GPU: {self.nodetier_resources.get('gpu_request', '?')}/{self.nodetier_resources.get('gpu_limit', '?')}",
f" PVCs: {', '.join(self.pvcs) if self.pvcs else 'None'}",
f" Init script: {'Yes' if self.init_script else 'No'}",
])
return "\n".join(lines)
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "back-btn":
self.app.pop_screen()
elif event.button.id == "apply-btn":
self.create_and_apply()
def create_and_apply(self):
folder_path = Path(self.folder).expanduser().resolve()
folder_path.mkdir(parents=True, exist_ok=True)
try:
# Write entrypoint.sh
entrypoint_path = folder_path / "entrypoint.sh"
with open(entrypoint_path, "w") as f:
f.write(self.entrypoint)
os.chmod(entrypoint_path, 0o755)
# Write init.sh if provided
has_init = bool(self.init_script)
if has_init:
init_path = folder_path / "init.sh"
with open(init_path, "w") as f:
f.write(self.init_script)
os.chmod(init_path, 0o755)
# Generate deploy.yaml using template
template_file = TEMPLATES_DIR / f"{self.resource_type.lower()}.yaml"
if not template_file.exists():
self.notify(f"Template not found: {template_file}", severity="error")
return
with open(template_file) as f:
template_content = f.read()
# Substitute variables
manifest = self._substitute_template(template_content, has_init)
deploy_path = folder_path / "deploy.yaml"
with open(deploy_path, "w") as f:
f.write(manifest)
self.notify(f"Files created in {folder_path}")