-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcli.py
More file actions
3822 lines (3284 loc) · 160 KB
/
Copy pathcli.py
File metadata and controls
3822 lines (3284 loc) · 160 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
"""
GPU Developer CLI - Main entry point
Reserve and manage GPU development servers
"""
import click
from typing import Optional
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich import print as rprint
from rich.spinner import Spinner
from rich.live import Live
from .auth import authenticate_user, validate_ssh_key_matches_github_user
from .reservations import (
ReservationManager,
_generate_vscode_command,
_add_agent_forwarding_to_ssh,
create_ssh_config_for_reservation,
remove_ssh_config_for_reservation,
get_ssh_config_path,
is_ssh_include_enabled,
)
from .config import Config, load_config
from .interactive import (
select_gpu_type_interactive,
select_gpu_count_interactive,
select_duration_interactive,
select_jupyter_interactive,
select_reservation_interactive,
ask_name_interactive,
select_edit_action_interactive,
ask_github_username_interactive,
ask_extension_hours_interactive,
check_interactive_support,
select_disk_interactive,
)
console = Console()
def _format_relative_time(timestamp_str: str, relative_to: str = "now") -> str:
"""Format timestamp as relative time if within 24h, otherwise absolute"""
if not timestamp_str or timestamp_str == "N/A":
return "N/A"
try:
from datetime import datetime, timezone, timedelta
# Parse the timestamp
if isinstance(timestamp_str, str):
if timestamp_str.endswith("Z"):
dt_utc = datetime.fromisoformat(
timestamp_str.replace("Z", "+00:00"))
elif "+" in timestamp_str or timestamp_str.endswith("00:00"):
dt_utc = datetime.fromisoformat(timestamp_str)
else:
naive_dt = datetime.fromisoformat(timestamp_str)
dt_utc = naive_dt.replace(tzinfo=timezone.utc)
else:
dt_utc = datetime.fromtimestamp(timestamp_str, tz=timezone.utc)
now = datetime.now(timezone.utc)
delta = dt_utc - now if relative_to == "expires" else now - dt_utc
# If more than 24 hours, use absolute time
if abs(delta.total_seconds()) > 24 * 3600:
dt_local = dt_utc.astimezone()
return dt_local.strftime("%Y-%m-%d %H:%M:%S")
# Format relative time
total_seconds = abs(delta.total_seconds())
if total_seconds < 60:
if relative_to == "expires":
return f"expires in {int(total_seconds)}s"
else:
return f"{int(total_seconds)}s ago"
elif total_seconds < 3600:
minutes = int(total_seconds // 60)
if relative_to == "expires":
return f"expires in {minutes}min"
else:
return f"{minutes}min ago"
else:
hours = int(total_seconds // 3600)
minutes = int((total_seconds % 3600) // 60)
if minutes > 0:
if relative_to == "expires":
return f"expires in {hours}h{minutes}min"
else:
return f"{hours}h{minutes}min ago"
else:
if relative_to == "expires":
return f"expires in {hours}h"
else:
return f"{hours}h ago"
except (ValueError, TypeError):
# Fallback to original format
return str(timestamp_str)[:19] if len(str(timestamp_str)) > 10 else str(timestamp_str)
def _format_expires_with_remaining(expires_at) -> str:
"""Format expiration time showing both absolute time and remaining time (for list view)"""
if not expires_at or expires_at == "N/A":
return "N/A"
try:
from datetime import datetime, timezone
# Parse the timestamp
if isinstance(expires_at, str):
if expires_at.endswith("Z"):
expires_dt_utc = datetime.fromisoformat(
expires_at.replace("Z", "+00:00"))
elif "+" in expires_at or expires_at.endswith("00:00"):
expires_dt_utc = datetime.fromisoformat(expires_at)
else:
naive_dt = datetime.fromisoformat(expires_at)
expires_dt_utc = naive_dt.replace(tzinfo=timezone.utc)
else:
# Legacy Unix timestamp
expires_dt_utc = datetime.fromtimestamp(expires_at, tz=timezone.utc)
# Convert to local timezone for display
expires_dt = expires_dt_utc.astimezone()
time_str = expires_dt.strftime("%H:%M")
# Calculate remaining time
now = datetime.now(timezone.utc)
delta = expires_dt_utc - now
total_seconds = delta.total_seconds()
if total_seconds <= 0:
return f"{time_str} (expired)"
# Format remaining time
hours = int(total_seconds // 3600)
minutes = int((total_seconds % 3600) // 60)
if hours > 0:
if minutes > 0:
remaining = f"{hours}h{minutes}m left"
else:
remaining = f"{hours}h left"
else:
remaining = f"{minutes}m left"
return f"{time_str} ({remaining})"
except (ValueError, TypeError):
return "Invalid"
def _show_single_reservation(connection_info: dict) -> None:
"""Display detailed information for a single reservation"""
status = connection_info.get("status", "unknown")
gpu_count = connection_info.get("gpu_count", 1)
gpu_type = connection_info.get("gpu_type", "Unknown")
instance_type = connection_info.get("instance_type", "unknown")
# Format GPU information
if gpu_type != "Unknown" and gpu_type != "unknown":
gpu_info = f"{gpu_count}x {gpu_type}"
else:
gpu_info = f"{gpu_count} GPU(s)"
# Format timestamps - only show launched_at (started time), not created time
launched_at = connection_info.get("launched_at", "N/A")
expires_at = connection_info.get("expires_at", "N/A")
# Get persistent disk status
ebs_volume_id = connection_info.get("ebs_volume_id", None)
has_persistent_disk = bool(ebs_volume_id and ebs_volume_id.strip())
# Convert timestamps to readable format
def format_timestamp(timestamp_str):
if not timestamp_str or timestamp_str == "N/A":
return "N/A"
try:
from datetime import datetime, timezone
if isinstance(timestamp_str, str):
# Handle different ISO format variations
if timestamp_str.endswith("Z"):
# Format: 2025-01-11T23:30:00Z
dt_utc = datetime.fromisoformat(
timestamp_str.replace("Z", "+00:00")
)
elif "+" in timestamp_str or timestamp_str.endswith("00:00"):
# Format: 2025-01-11T23:30:00+00:00
dt_utc = datetime.fromisoformat(timestamp_str)
else:
# Format: 2025-01-11T23:30:00 (naive datetime, assume UTC)
naive_dt = datetime.fromisoformat(timestamp_str)
dt_utc = naive_dt.replace(tzinfo=timezone.utc)
dt_local = dt_utc.astimezone() # Convert to local timezone
return dt_local.strftime("%Y-%m-%d %H:%M:%S")
else:
# Legacy Unix timestamp
dt = datetime.fromtimestamp(timestamp_str)
return dt.strftime("%Y-%m-%d %H:%M:%S")
except (ValueError, TypeError):
return str(timestamp_str)[:19] # Fallback to first 19 chars
launched_formatted = _format_relative_time(launched_at, "now")
expires_formatted = _format_relative_time(expires_at, "expires")
# Format persistent disk status - show disk name if available
disk_name = connection_info.get("disk_name")
if disk_name:
disk_status = f"Persistent (disk: {disk_name})"
elif has_persistent_disk:
disk_status = "Persistent"
else:
disk_status = "Temporary"
if status == "active":
jupyter_info = ""
if connection_info.get("jupyter_enabled") and connection_info.get(
"jupyter_url"
):
jupyter_info = (
f"[blue]Jupyter Lab:[/blue] {connection_info['jupyter_url']}\n"
)
elif connection_info.get("jupyter_enabled") and not connection_info.get(
"jupyter_url"
):
jupyter_info = (
f"[blue]Jupyter Lab:[/blue] [yellow]Starting...[/yellow]\n"
)
else:
# Show enable command if Jupyter is not enabled
short_id = connection_info["reservation_id"][:8]
jupyter_info = f"[dim]Jupyter Lab:[/dim] [yellow]Not enabled[/yellow] [dim]→[/dim] [cyan]gpu-dev edit {short_id} --enable-jupyter[/cyan]\n"
# Format secondary users information
secondary_users = connection_info.get("secondary_users", [])
secondary_users_info = ""
if secondary_users:
users_list = ", ".join(secondary_users)
secondary_users_info = (
f"[blue]Secondary Users:[/blue] {users_list}\n"
)
else:
# Show add-user command if no secondary users
short_id = connection_info["reservation_id"][:8]
secondary_users_info = f"[dim]Secondary Users:[/dim] [yellow]None[/yellow] [dim]→[/dim] [cyan]gpu-dev edit {short_id} --add-user <github_username>[/cyan]\n"
# Generate VS Code command
vscode_command = _generate_vscode_command(
connection_info["ssh_command"]
)
vscode_info = ""
if vscode_command:
vscode_info = f"[blue]VS Code Remote:[/blue] {vscode_command}\n"
# Add agent forwarding to SSH command for display
ssh_with_forwarding = _add_agent_forwarding_to_ssh(
connection_info["ssh_command"]
)
# Generate convenience connect command
short_id = connection_info["reservation_id"][:8]
connect_command = f"[cyan]gpu-dev connect {short_id}[/cyan]"
# Get SSH config path for this reservation
reservation_id = connection_info["reservation_id"]
reservation_name = connection_info.get("name")
pod_name = connection_info.get("pod_name", "")
ssh_config_path = get_ssh_config_path(reservation_id, reservation_name)
use_include = is_ssh_include_enabled()
# Use SSH config in commands if it exists
from pathlib import Path
if Path(ssh_config_path).exists() and pod_name:
if use_include:
# User approved Include - show simple commands
from .reservations import _make_vscode_link
ssh_command_display = f"[green]ssh {pod_name}[/green]"
vscode_url = _make_vscode_link(pod_name)
vscode_cmd_text = f"code --remote ssh-remote+{pod_name} /home/dev"
vscode_command_display = f"[link={vscode_url}][green]{vscode_cmd_text}[/green][/link]"
vscode_info = f"[blue]VS Code Remote:[/blue] {vscode_command_display}\n"
else:
# User declined Include - show commands with -F flag
ssh_command_display = f"[green]ssh -F {ssh_config_path} {pod_name}[/green]"
vscode_command_display = f"Add [green]Include ~/.gpu-dev/*-sshconfig[/green] to ~/.ssh/config and ~/.cursor/ssh_config (or: [green]gpu-dev config ssh-include enable[/green])"
vscode_info = f"[blue]VS Code/Cursor:[/blue] {vscode_command_display}\n"
else:
# Fallback to full commands if SSH config doesn't exist
ssh_command_display = ssh_with_forwarding
vscode_command_display = vscode_command if vscode_command else ""
vscode_info = f"[blue]VS Code Remote:[/blue] {vscode_command_display}\n" if vscode_command_display else ""
# Check for warnings
warning_message = connection_info.get("warning", "")
warning_section = ""
if warning_message:
warning_section = f"\n\n{warning_message}"
# Check for OOM events
oom_count = connection_info.get("oom_count", 0)
last_oom_at = connection_info.get("last_oom_at")
oom_section = ""
if oom_count and int(oom_count) > 0:
oom_time_display = format_timestamp(last_oom_at) if last_oom_at else "Unknown"
oom_section = f"\n[red]⚠️ OOM Events:[/red] [red]{oom_count} OOM(s) detected (last: {oom_time_display})[/red]"
panel_content = (
f"[green]Reservation Details[/green]\n\n"
f"[blue]Quick Connect:[/blue] {connect_command}\n"
f"[blue]SSH Command:[/blue] {ssh_command_display}\n"
+ vscode_info
+ jupyter_info
+ f"[blue]Pod Name:[/blue] {connection_info['pod_name']}\n"
f"[blue]GPUs:[/blue] {gpu_info}\n"
f"[blue]Instance Type:[/blue] {instance_type}\n"
+ secondary_users_info
+ f"[blue]Storage:[/blue] {disk_status}\n"
f"[blue]Started:[/blue] {launched_formatted}\n"
f"[blue]Expires:[/blue] {expires_formatted}"
+ oom_section
+ warning_section
)
panel = Panel.fit(panel_content, title="🚀 Active Reservation")
console.print(panel)
elif status in ["queued", "pending", "preparing"]:
panel_content = (
f"[yellow]Reservation Details[/yellow]\n\n"
f"[blue]Status:[/blue] {status.title()}\n"
f"[blue]GPUs Requested:[/blue] {gpu_info}\n"
f"[blue]Storage:[/blue] {disk_status}\n"
f"[blue]Expected Instance:[/blue] {instance_type if instance_type != 'unknown' else 'TBD'}"
)
if status == "preparing":
panel_content += f"\n[blue]Pod Name:[/blue] {connection_info.get('pod_name', 'N/A')}"
# Show current detailed status from unified status tracking
current_detailed_status = connection_info.get(
"current_detailed_status", "")
if current_detailed_status:
panel_content += (
f"\n[blue]Current Status:[/blue] {current_detailed_status}"
)
panel = Panel.fit(
panel_content, title=f"⏳ {status.title()} Reservation"
)
console.print(panel)
if status == "queued":
rprint(
"[yellow]💡 SSH access will be available once your reservation becomes active[/yellow]"
)
elif status == "preparing":
rprint(
"[yellow]💡 Your environment is being prepared. SSH access will be available shortly.[/yellow]"
)
else:
panel_content = (
f"[red]Reservation Details[/red]\n\n"
f"[blue]Status:[/blue] {status.title()}\n"
f"[blue]GPUs:[/blue] {gpu_info}\n"
f"[blue]Storage:[/blue] {disk_status}\n"
f"[blue]Started:[/blue] {launched_formatted}\n"
f"[blue]Ended:[/blue] {expires_formatted}"
)
# Show failure reason for failed reservations
if status == "failed":
failure_reason = connection_info.get(
"failure_reason",
connection_info.get("current_detailed_status", "Unknown error")
)
panel_content += f"\n[blue]Error:[/blue] {failure_reason}"
panel = Panel.fit(
panel_content, title=f"📋 {status.title()} Reservation"
)
console.print(panel)
# Show pod logs for failed reservations
if status == "failed":
pod_logs = connection_info.get("pod_logs", "")
if pod_logs and pod_logs.strip():
from rich.text import Text
rprint("\n[red]🔍 Pod logs (last 20 lines) - Details:[/red]")
# Create logs panel
log_text = Text(pod_logs)
log_panel = Panel(
log_text,
title="🐚 Container Startup Logs",
title_align="left",
border_style="red",
expand=False,
)
console.print(log_panel)
def _validate_ssh_key_or_exit(config: Config, live: Live) -> bool:
"""
Validate SSH key matches configured GitHub username.
Returns True if valid, False if validation failed (and exits with error messages).
"""
validation_result = validate_ssh_key_matches_github_user(config, live)
if not validation_result["valid"]:
live.stop()
rprint("[red]❌ Github SSH key validation failed[/red]")
# Provide helpful suggestions
if validation_result["ssh_user"] and validation_result["configured_user"]:
rprint("\n[yellow]💡 Fix by updating your config:[/yellow]")
rprint(
" [cyan]gpu-dev config set github_user {validation_result['ssh_user']}[/cyan]"
)
elif not validation_result["configured_user"]:
rprint("\n[yellow]💡 Fix by configuring your GitHub username:[/yellow]")
rprint(
" [cyan]gpu-dev config set github_user <your-github-username>[/cyan]"
)
else:
rprint("\n[yellow]💡 gpu-dev utilizes Github keys for auth![/yellow]")
rprint(
"[yellow]💡 Check https://fburl.com/gh-ssh for info on how to add your ssh key to Github[/yellow]"
)
return False
return True
@click.group()
@click.version_option(package_name="gpu-dev")
@click.pass_context
def main(ctx: click.Context) -> None:
"""\b
GPU Developer CLI - Reserve and manage GPU development servers
Reserve GPU-enabled development environments with SSH access.
Supports 1, 2, 4, 8, or 16 GPU configurations with automatic resource management.
\b
Interactive Mode (NEW):
gpu-dev reserve # Interactive reservation (auto-detected)
gpu-dev cancel # Interactive cancellation
gpu-dev edit # Interactive edit
\b
Command-line Mode:
gpu-dev reserve --gpus 2 --hours 4 # Reserve 2 GPUs for 4 hours
gpu-dev reserve --jupyter # Reserve with Jupyter Lab
gpu-dev cancel abc12345 # Cancel specific reservation
gpu-dev edit abc12345 --enable-jupyter # Enable Jupyter on reservation
\b
Information Commands:
gpu-dev list # Check your reservations
gpu-dev show # Show detailed info for active/pending reservations
gpu-dev show abc12345 # Get detailed reservation info
gpu-dev connect # Connect to active reservation via SSH
gpu-dev avail # Check GPU availability by type
gpu-dev status # Check cluster status
gpu-dev help # Show this help message
\b
Configuration:
gpu-dev config ssh-include enable # Enable SSH config auto-include
gpu-dev config ssh-include disable # Disable SSH config auto-include
Interactive mode is automatically enabled when running commands without
parameters in a terminal. Use --no-interactive to disable.
Use 'gpu-dev <command> --help' for detailed help on each command.
"""
ctx.ensure_object(dict)
@main.command()
@click.option(
"--gpus",
"-g",
type=click.Choice(["1", "2", "4", "8", "12", "16",
"20", "24", "32", "40", "48"]),
help="Number of GPUs to reserve (multiples of max-per-node for multinode setups)",
)
@click.option(
"--gpu-type",
"-t",
type=click.Choice(
["b200", "h200", "h100", "a100", "a10g", "t4", "l4", "t4-small", "cpu-arm", "cpu-x86"], case_sensitive=False
),
help="GPU type to reserve (b200/h200/h100/a100/a10g/t4/l4/t4-small/cpu-arm/cpu-x86)",
)
@click.option(
"--hours",
"-h",
type=float,
help="Reservation duration in hours (supports decimals, max 24)",
)
@click.option("--name", "-n", type=str, help="Optional name for the reservation")
@click.option(
"--jupyter",
is_flag=True,
help="Enable Jupyter Lab access (can be enabled later with 'gpu-dev edit')",
)
@click.option(
"--ignore-no-persist",
is_flag=True,
help="Skip persistent disk warning for multiple reservations",
)
@click.option(
"--no-persist",
is_flag=True,
help="Create reservation without persistent disk",
)
@click.option(
"--recreate-env",
is_flag=True,
help="Recreate shell environment (bashrc/zshrc/oh-my-zsh) even on existing persistent disk",
)
@click.option(
"--interactive/--no-interactive",
default=None,
help="Force interactive mode on/off (auto-detected by default)",
)
@click.option(
"--distributed",
"-d",
is_flag=True,
help="Required flag for multinode GPU reservations (> single node max)",
)
@click.option(
"--verbose",
"-v",
is_flag=True,
help="Enable verbose debug output",
)
@click.option(
"--dockerfile",
type=click.Path(exists=True, readable=True),
help="Path to custom Dockerfile to use instead of default container image (max 512KB)",
)
@click.option(
"--dockerimage",
type=str,
help="Custom Docker image to use instead of default container image (e.g., pytorch/pytorch:2.0.1-cuda11.7-cudnn8-devel)",
)
@click.option(
"--preserve-entrypoint",
is_flag=True,
help="Preserve the original container ENTRYPOINT/CMD instead of overriding with bash script",
)
@click.option(
"--disk",
type=str,
help="Named persistent disk to use (e.g., 'pytorch-main'), or 'none' for temporary storage only. Use 'gpu-dev disk list' to see available disks.",
)
@click.option(
"--node-label",
"-l",
type=str,
multiple=True,
help="Request nodes with specific label (format: key=value). Example: --node-label nsight=true for Nsight profiling nodes",
)
@click.pass_context
def reserve(
ctx: click.Context,
gpus: Optional[str],
gpu_type: Optional[str],
hours: Optional[float],
name: Optional[str],
jupyter: bool,
ignore_no_persist: bool,
no_persist: bool,
recreate_env: bool,
interactive: Optional[bool],
distributed: bool,
verbose: bool,
dockerfile: Optional[str],
dockerimage: Optional[str],
preserve_entrypoint: bool,
disk: Optional[str],
node_label: tuple,
) -> None:
"""Reserve GPU development server(s)
Creates a reservation for GPU-enabled development environment with SSH access.
The environment includes PyTorch, CUDA, and common ML tools pre-installed.
\b
Interactive Mode (NEW):
gpu-dev reserve # Interactive mode - guided setup
The interactive mode will:
- Show GPU availability table
- Let you select GPU type with arrow keys
- Choose number of GPUs
- Select duration with presets
- Optional Jupyter Lab and naming
\b
Command-line Mode:
gpu-dev reserve -g 4 -h 2.5 # 4 GPUs for 2.5 hours
gpu-dev reserve -g 8 -h 12 -n "training" # 8 GPUs, named reservation
gpu-dev reserve --jupyter # Include Jupyter Lab access
gpu-dev reserve --gpu-type h200 -g 2 # 2 H200 GPUs
gpu-dev reserve -g 16 --distributed # 16 GPUs (2 nodes), required for multinode
GPU Options:
Single-node: 1, 2, 4, 8 GPUs (depending on GPU type)
Multinode: Multiples of max GPUs per node (e.g., 16=2×8, 24=3×8 for H100)
Authentication: Uses your AWS credentials and GitHub SSH keys
"""
try:
# Handle --disk none (case insensitive) to explicitly request no persistent disk
explicit_no_disk_from_param = False
if disk and disk.lower() == "none":
explicit_no_disk_from_param = True
disk = None
# Determine if we should use interactive mode
use_interactive = interactive
if use_interactive is None:
# Auto-detect: use interactive if no key parameters provided
# For CPU instances, gpus parameter is optional (defaults to 0)
gpu_required = gpus is None and (
gpu_type is None or not gpu_type.lower().startswith("cpu-"))
use_interactive = (
gpu_required or gpu_type is None or hours is None
) and check_interactive_support()
# GPU config for validation (includes CPU-only instances)
gpu_configs = {
"t4": {"max_gpus": 4, "instance_type": "g4dn.12xlarge"},
"l4": {"max_gpus": 4, "instance_type": "g6.12xlarge"},
"a10g": {"max_gpus": 4, "instance_type": "g5.12xlarge"},
"t4-small": {"max_gpus": 1, "instance_type": "g4dn.xlarge"},
"a100": {"max_gpus": 8, "instance_type": "p4d.24xlarge"},
"h100": {"max_gpus": 8, "instance_type": "p5.48xlarge"},
"h200": {"max_gpus": 8, "instance_type": "p5e.48xlarge"},
"b200": {"max_gpus": 8, "instance_type": "p6-b200.48xlarge"},
"cpu-arm": {"max_gpus": 0, "instance_type": "c7g.4xlarge"},
"cpu-x86": {"max_gpus": 0, "instance_type": "c7i.4xlarge"},
}
# Early validation of GPU type to extract max_gpus (needed for disk selection)
if gpu_type:
gpu_type = gpu_type.lower()
if gpu_type not in gpu_configs:
valid_types = ", ".join(sorted(gpu_configs.keys()))
rprint(
f"[red]❌ Invalid GPU type '{gpu_type}'. Valid types: {valid_types}[/red]"
)
return
max_gpus = gpu_configs[gpu_type]["max_gpus"]
else:
max_gpus = None # Will be set later in interactive mode
if use_interactive:
# Interactive mode - gather parameters interactively
rprint("[cyan]🎯 Interactive reservation mode[/cyan]")
rprint(
"[dim]Use --no-interactive flag to disable interactive mode[/dim]\n")
# Setup config early for availability check
with Live(
Spinner("dots", text="📡 Loading GPU availability..."), console=console
) as live:
config = load_config()
try:
user_info = authenticate_user(config)
except RuntimeError as e:
live.stop()
rprint(f"[red]❌ {str(e)}[/red]")
return
# Validate SSH key matches configured GitHub username
live.update(Spinner("dots", text="🔐 Validating SSH key..."))
if not _validate_ssh_key_or_exit(config, live):
return
live.update(
Spinner("dots", text="📡 Loading GPU availability..."))
reservation_mgr = ReservationManager(config)
availability_info = reservation_mgr.get_gpu_availability_by_type()
live.stop()
if not availability_info:
rprint("[red]❌ Could not get GPU availability information[/red]")
return
# Interactive GPU type selection
if gpu_type is None:
gpu_type = select_gpu_type_interactive(availability_info)
if gpu_type is None:
rprint("[yellow]Reservation cancelled.[/yellow]")
return
# Interactive GPU count selection
if gpus is None:
gpu_type_lower = gpu_type.lower()
if gpu_type_lower not in gpu_configs:
rprint(f"[red]❌ Invalid GPU type '{gpu_type}'[/red]")
return
max_gpus = gpu_configs[gpu_type_lower]["max_gpus"]
gpu_count = select_gpu_count_interactive(
gpu_type_lower, max_gpus)
if gpu_count is None:
rprint("[yellow]Reservation cancelled.[/yellow]")
return
# Show distributed warning for interactive multinode selections (always show)
if gpu_count > max_gpus:
num_nodes = gpu_count // max_gpus
rprint(
f"\n[yellow]⚠️ You selected {gpu_count} GPUs. This is supported for distributed workflows.[/yellow]")
rprint(
f"[yellow]This will reserve {num_nodes} pods that have:[/yellow]")
rprint("[yellow]• A shared network drive[/yellow]")
rprint("[yellow]• Network connectivity to each other[/yellow]")
rprint(
f"[yellow]• Hostname resolution (<podname>-headless.gpu-dev.svc.cluster.local)[/yellow]")
rprint(
f"[yellow]• Master port 29500 available on all nodes[/yellow]\n")
try:
choice = click.confirm(
"Do you want to continue?", default=False)
if not choice:
rprint(
"[yellow]Reservation cancelled by user[/yellow]")
return
except (KeyboardInterrupt, click.Abort):
rprint(
"\n[yellow]Reservation cancelled by user[/yellow]")
return
else:
gpu_count = int(gpus)
# Track if user explicitly requests no persistent disk
explicit_no_disk = explicit_no_disk_from_param
# Interactive disk selection (if not multinode - only master node gets persistent disk)
# This comes BEFORE duration so user knows what they're reserving
if disk is None and gpu_count <= max_gpus and not explicit_no_disk_from_param: # Single node only
disk = select_disk_interactive(user_info["user_id"], config)
# Check if user cancelled
if disk == "__cancelled__":
rprint("[yellow]Reservation cancelled.[/yellow]")
return
# Check if user explicitly chose "no disk"
if disk == "__no_disk__":
explicit_no_disk = True
disk = None
# Interactive duration selection
if hours is None:
hours = select_duration_interactive(gpu_type=gpu_type)
if hours is None:
rprint("[yellow]Reservation cancelled.[/yellow]")
return
# Interactive Jupyter selection (if not already set via flag)
if not jupyter: # Only ask if not already enabled via flag
jupyter_interactive = select_jupyter_interactive()
if jupyter_interactive is None:
rprint("[yellow]Reservation cancelled.[/yellow]")
return
jupyter = jupyter_interactive
# Interactive name selection
if name is None:
name = ask_name_interactive()
# name can be None, that's fine
else:
# Non-interactive mode - use defaults and validate
if gpu_type is None:
gpu_type = "a100"
if hours is None:
hours = 8.0
# Set default GPU count based on GPU type
if gpus is None:
if gpu_type and gpu_type.lower().startswith("cpu-"):
gpus = "0" # CPU instances default to 0 GPUs
else:
gpus = "1" # GPU instances default to 1 GPU
gpu_count = int(gpus)
# Non-interactive disk selection (if not specified via flag)
# Only for single-node reservations
if disk is None and max_gpus is not None and gpu_count <= max_gpus and not explicit_no_disk_from_param:
# In non-interactive mode, check if terminal supports interactive prompts
if check_interactive_support():
# Load config and authenticate if not already done
if 'config' not in locals():
config = load_config()
try:
user_info = authenticate_user(config)
except RuntimeError as e:
rprint(f"[red]❌ {str(e)}[/red]")
return
disk = select_disk_interactive(user_info["user_id"], config)
# Check if user cancelled
if disk == "__cancelled__":
rprint("[yellow]Reservation cancelled.[/yellow]")
return
# Check if user explicitly chose "no disk"
if disk == "__no_disk__":
explicit_no_disk = True
disk = None
# Otherwise leave disk as None (no persistent disk)
# Validate GPU type and count (for both modes)
# GPU type already validated earlier, just extract max_gpus if not already set
if max_gpus is None:
gpu_type = gpu_type.lower()
if gpu_type not in gpu_configs:
valid_types = ", ".join(sorted(gpu_configs.keys()))
rprint(
f"[red]❌ Invalid GPU type '{gpu_type}'. Valid types: {valid_types}[/red]"
)
return
max_gpus = gpu_configs[gpu_type]["max_gpus"]
elif gpu_type:
gpu_type = gpu_type.lower() # Ensure normalized
# Special validation for CPU-only instances
if gpu_type.startswith("cpu-"):
if gpu_count != 0:
rprint(
f"[red]❌ CPU-only instances must have --gpus=0 or omit --gpus, not {gpu_count}[/red]")
return
elif gpu_count == 0:
rprint(
f"[red]❌ GPU type '{gpu_type}' must have --gpus > 0. Use cpu-arm or cpu-x86 for CPU-only instances[/red]")
return
# Check if this is a multinode request
if gpu_count > max_gpus:
# Validate that it's a valid multiple for multinode
if gpu_count % max_gpus != 0:
rprint(
f"[red]❌ For multinode deployments, GPU count must be a multiple of {max_gpus} (max per node for {gpu_type})[/red]"
)
rprint(
f"[yellow]Valid counts: {max_gpus}, {max_gpus*2}, {max_gpus*3}, etc.[/yellow]")
return
# Calculate number of nodes needed
num_nodes = gpu_count // max_gpus
# For non-interactive mode, require --distributed flag
if not use_interactive and not distributed:
rprint(
f"\n[red]❌ Multinode GPU reservations require the --distributed flag[/red]")
rprint(
f"[yellow]You requested {gpu_count} GPUs ({num_nodes} nodes × {max_gpus} GPUs)[/yellow]")
rprint(f"[yellow]This creates a distributed setup with:[/yellow]")
rprint("[yellow]• Shared network drive between nodes[/yellow]")
rprint("[yellow]• Network connectivity between pods[/yellow]")
rprint(
f"[yellow]• Hostname resolution (<podname>-headless.gpu-dev.svc.cluster.local)[/yellow]")
rprint(
f"[yellow]• Master port 29500 available on all nodes[/yellow]")
rprint(
f"\n[cyan]Add --distributed to proceed: gpu-dev reserve -g {gpu_count} --distributed[/cyan]")
return
# Validate parameters (CPU types have no duration limit)
is_cpu_type = gpu_type and gpu_type.startswith("cpu-")
if not is_cpu_type and hours > 24:
rprint("[red]Maximum reservation time is 24 hours for GPU instances[/red]")
return
if hours < 0.0833: # Less than 5 minutes
rprint(
"[red]❌ Minimum reservation time is 5 minutes (0.0833 hours)[/red]")
return
# Validate Docker options
if dockerfile and dockerimage:
rprint("[red]❌ Cannot specify both --dockerfile and --dockerimage[/red]")
return
# Process Dockerfile if provided
dockerfile_s3_key = None
if dockerfile:
try:
import os
import tarfile
import tempfile
import uuid
# Check file size (512KB limit for individual Dockerfile)
file_size = os.path.getsize(dockerfile)
if file_size > 512 * 1024:
rprint(
f"[red]❌ Dockerfile too large: {file_size} bytes (max 512KB)[/red]")
return
# Create build context (Dockerfile + any files in same directory)
dockerfile_dir = os.path.dirname(os.path.abspath(dockerfile))
dockerfile_name = os.path.basename(dockerfile)
rprint(
f"[cyan]📦 Creating build context from {dockerfile_dir}[/cyan]")
# Create a temporary tar.gz with the build context
with tempfile.NamedTemporaryFile(suffix='.tar.gz', delete=False) as temp_tar:
with tarfile.open(temp_tar.name, 'w:gz') as tar:
# Add all files from the Dockerfile directory
for root, dirs, files in os.walk(dockerfile_dir):
for file in files:
file_path = os.path.join(root, file)
# Calculate relative path from dockerfile_dir
arcname = os.path.relpath(
file_path, dockerfile_dir)
tar.add(file_path, arcname=arcname)
# Ensure Dockerfile is at root with standard name if needed
if dockerfile_name.lower() != 'dockerfile':
dockerfile_path = os.path.join(
dockerfile_dir, dockerfile_name)
tar.add(dockerfile_path, arcname='Dockerfile')
# Check compressed size limit (SQS has 1 MiB limit, base64 adds ~33% overhead)
compressed_size = os.path.getsize(temp_tar.name)
# ~700KB to allow for base64 overhead and other message fields
max_tar_size = 700 * 1024
if compressed_size > max_tar_size:
os.unlink(temp_tar.name)
rprint(
f"[red]❌ Build context too large: {compressed_size} bytes (max ~700KB compressed)[/red]")
return
# Base64 encode the tar.gz for SQS message
import base64
with open(temp_tar.name, 'rb') as f:
build_context_data = base64.b64encode(
f.read()).decode('utf-8')
dockerfile_s3_key = build_context_data # Pass base64 data instead of S3 key
# Cleanup temp file
os.unlink(temp_tar.name)
rprint(
f"[green]✅ Build context prepared: {compressed_size} bytes compressed[/green]")
except Exception as e:
rprint(f"[red]❌ Error processing Dockerfile: {str(e)}[/red]")
return
# Use a single spinner context for the entire process
with Live(
Spinner("dots", text="📡 Starting reservation process..."), console=console
) as live:
# Setup config and reservation manager
if use_interactive:
# Already have config, user_info, and reservation_mgr from interactive setup
pass
else:
# Load config for non-interactive mode
live.update(
Spinner("dots", text="📡 Contacting reservation service...")
)
config = load_config()
live.update(Spinner("dots", text="📡 Authenticating..."))
# Authenticate using AWS credentials - if you can call AWS, you're authorized
try:
user_info = authenticate_user(config)
except RuntimeError as e:
live.stop()
rprint(f"[red]❌ {str(e)}[/red]")
return
# Validate SSH key matches configured GitHub username
live.update(Spinner("dots", text="🔐 Validating SSH key..."))
if not _validate_ssh_key_or_exit(config, live):
return
# Track if user explicitly requests no persistent disk
explicit_no_disk = explicit_no_disk_from_param
# Validate disk if specified
if disk:
from .disks import list_disks
existing_disks = list_disks(user_info["user_id"], config)