dayhoff-tools 1.3.16__py3-none-any.whl → 1.3.17__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,6 +18,7 @@ from rich.panel import Panel
18
18
  from rich.progress import Progress, SpinnerColumn, TextColumn
19
19
  from rich.prompt import Confirm, IntPrompt, Prompt
20
20
  from rich.table import Table
21
+ import re
21
22
 
22
23
  # Initialize Typer apps
23
24
  engine_app = typer.Typer(help="Manage compute engines for development.")
@@ -37,6 +38,41 @@ HOURLY_COSTS = {
37
38
  # SSH config management
38
39
  SSH_MANAGED_COMMENT = "# Managed by dh engine"
39
40
 
41
+ # --------------------------------------------------------------------------------
42
+ # Bootstrap stage helpers
43
+ # --------------------------------------------------------------------------------
44
+
45
+ def _colour_stage(stage: str) -> str:
46
+ """Return colourised stage name for table output."""
47
+ if not stage:
48
+ return "[dim]-[/dim]"
49
+ low = stage.lower()
50
+ if low.startswith("error"):
51
+ return f"[red]{stage}[/red]"
52
+ if low == "finished":
53
+ return f"[green]{stage}[/green]"
54
+ return f"[yellow]{stage}[/yellow]"
55
+
56
+
57
+ def _fetch_init_stages(instance_ids: List[str]) -> Dict[str, str]:
58
+ """Fetch DayhoffInitStage tag for many instances in one call."""
59
+ if not instance_ids:
60
+ return {}
61
+ ec2 = boto3.client("ec2", region_name="us-east-1")
62
+ stages: Dict[str, str] = {}
63
+ try:
64
+ paginator = ec2.get_paginator("describe_instances")
65
+ for page in paginator.paginate(InstanceIds=instance_ids):
66
+ for res in page["Reservations"]:
67
+ for inst in res["Instances"]:
68
+ iid = inst["InstanceId"]
69
+ tag_val = next((t["Value"] for t in inst.get("Tags", []) if t["Key"] == "DayhoffInitStage"), None)
70
+ if tag_val:
71
+ stages[iid] = tag_val
72
+ except Exception:
73
+ pass # best-effort
74
+ return stages
75
+
40
76
 
41
77
  def check_aws_sso() -> str:
42
78
  """Check AWS SSO status and return username."""
@@ -486,6 +522,9 @@ def list_engines(
486
522
  console.print("No engines found.")
487
523
  return
488
524
 
525
+ # Fetch bootstrap stages once
526
+ stages_map = _fetch_init_stages([e["instance_id"] for e in engines])
527
+
489
528
  # Create table
490
529
  table = Table(title="Engines", box=box.ROUNDED)
491
530
  table.add_column("Name", style="cyan")
@@ -493,6 +532,7 @@ def list_engines(
493
532
  table.add_column("Type")
494
533
  table.add_column("User")
495
534
  table.add_column("Status")
535
+ table.add_column("Stage")
496
536
  table.add_column("Disk Usage")
497
537
  table.add_column("Uptime/Since")
498
538
  table.add_column("$/hour", justify="right")
@@ -515,12 +555,15 @@ def list_engines(
515
555
  time_str = launch_time.strftime("%Y-%m-%d %H:%M")
516
556
  disk_usage = "-"
517
557
 
558
+ stage_display = _colour_stage(stages_map.get(engine["instance_id"], "-"))
559
+
518
560
  table.add_row(
519
561
  engine["name"],
520
562
  engine["instance_id"],
521
563
  engine["engine_type"],
522
564
  engine["user"],
523
565
  format_status(engine["state"], engine.get("ready")),
566
+ stage_display,
524
567
  disk_usage,
525
568
  time_str,
526
569
  f"${hourly_cost:.2f}",
@@ -566,18 +609,43 @@ def engine_status(
566
609
  hourly_cost = HOURLY_COSTS.get(engine["engine_type"], 0)
567
610
  total_cost = hourly_cost * (uptime.total_seconds() / 3600)
568
611
 
569
- # Create status panel
612
+ stages_map = _fetch_init_stages([engine["instance_id"]])
613
+ stage_val = stages_map.get(engine["instance_id"], "-")
614
+
570
615
  status_lines = [
571
616
  f"[bold]Name:[/bold] {engine['name']}",
572
617
  f"[bold]Instance:[/bold] {engine['instance_id']}",
573
618
  f"[bold]Type:[/bold] {engine['engine_type']} ({engine['instance_type']})",
574
619
  f"[bold]Status:[/bold] {format_status(engine['state'], engine.get('ready'))}",
620
+ f"[bold]Bootstrap:[/bold] {_colour_stage(stage_val)}",
575
621
  f"[bold]User:[/bold] {engine['user']}",
576
622
  f"[bold]IP:[/bold] {engine.get('public_ip', 'N/A')}",
577
623
  f"[bold]Launched:[/bold] {launch_time.strftime('%Y-%m-%d %H:%M:%S')} ({format_duration(uptime)} ago)",
578
624
  f"[bold]Cost:[/bold] ${hourly_cost:.2f}/hour (${total_cost:.2f} total)",
579
625
  ]
580
626
 
627
+ # Health report (only if bootstrap finished)
628
+ if stage_val == "finished":
629
+ try:
630
+ ssm = boto3.client("ssm", region_name="us-east-1")
631
+ res = ssm.send_command(
632
+ InstanceIds=[engine["instance_id"]],
633
+ DocumentName="AWS-RunShellScript",
634
+ Parameters={"commands": ["cat /var/run/engine-health.json || true"], "executionTimeout": ["10"]},
635
+ )
636
+ cid = res["Command"]["CommandId"]
637
+ time.sleep(1)
638
+ inv = ssm.get_command_invocation(CommandId=cid, InstanceId=engine["instance_id"])
639
+ if inv["Status"] == "Success":
640
+ import json as _json
641
+ health = _json.loads(inv["StandardOutputContent"].strip() or "{}")
642
+ status_lines.append("")
643
+ status_lines.append("[bold]Health:[/bold]")
644
+ status_lines.append(f" • GPU Drivers: {'OK' if health.get('drivers_ok') else 'MISSING'}")
645
+ status_lines.append(f" • Idle Detector: {health.get('idle_detector_timer', 'unknown')}")
646
+ except Exception:
647
+ pass
648
+
581
649
  if attached_studios:
582
650
  status_lines.append("")
583
651
  status_lines.append("[bold]Attached Studios:[/bold]")
@@ -1909,3 +1977,72 @@ def resize_studio(
1909
1977
 
1910
1978
  console.print("\n[dim]The filesystem will be automatically expanded when you next attach the studio.[/dim]")
1911
1979
  console.print(f"To attach: [cyan]dh studio attach <engine-name>[/cyan]")
1980
+
1981
+ # ================= Idle timeout command =================
1982
+
1983
+
1984
+ @engine_app.command("idle-timeout")
1985
+ def idle_timeout_cmd(
1986
+ name_or_id: str = typer.Argument(help="Engine name or instance ID"),
1987
+ set: Optional[str] = typer.Option(None, "--set", "-s", help="New timeout (e.g., 2h30m, 45m)")
1988
+ ):
1989
+ """Show or set the engine idle-detector timeout."""
1990
+ check_aws_sso()
1991
+
1992
+ # Resolve engine
1993
+ response = make_api_request("GET", "/engines")
1994
+ if response.status_code != 200:
1995
+ console.print("[red]❌ Failed to fetch engines[/red]")
1996
+ raise typer.Exit(1)
1997
+
1998
+ engines = response.json().get("engines", [])
1999
+ engine = resolve_engine(name_or_id, engines)
2000
+
2001
+ ssm = boto3.client("ssm", region_name="us-east-1")
2002
+
2003
+ if set is None:
2004
+ # Show current
2005
+ resp = ssm.send_command(
2006
+ InstanceIds=[engine["instance_id"]],
2007
+ DocumentName="AWS-RunShellScript",
2008
+ Parameters={"commands": ["grep -E '^IDLE_TIMEOUT_SECONDS=' /etc/engine.env || echo 'IDLE_TIMEOUT_SECONDS=1800'"], "executionTimeout": ["10"]},
2009
+ )
2010
+ cid = resp["Command"]["CommandId"]
2011
+ time.sleep(1)
2012
+ inv = ssm.get_command_invocation(CommandId=cid, InstanceId=engine["instance_id"])
2013
+ if inv["Status"] == "Success":
2014
+ line = inv["StandardOutputContent"].strip()
2015
+ secs = int(line.split("=")[1]) if "=" in line else 1800
2016
+ console.print(f"Current idle timeout: {secs//60}m ({secs} seconds)")
2017
+ else:
2018
+ console.print("[red]❌ Could not retrieve idle timeout[/red]")
2019
+ return
2020
+
2021
+ # ----- set new value -----
2022
+ m = re.match(r"^(?:(\d+)h)?(?:(\d+)m)?$", set)
2023
+ if not m:
2024
+ console.print("[red]❌ Invalid duration format. Use e.g. 2h, 45m, 1h30m[/red]")
2025
+ raise typer.Exit(1)
2026
+ hours = int(m.group(1) or 0)
2027
+ minutes = int(m.group(2) or 0)
2028
+ seconds = hours * 3600 + minutes * 60
2029
+ if seconds == 0:
2030
+ console.print("[red]❌ Duration must be greater than zero[/red]")
2031
+ raise typer.Exit(1)
2032
+
2033
+ console.print(f"Setting idle timeout to {set} ({seconds} seconds)…")
2034
+
2035
+ cmd = (
2036
+ "sudo sed -i '/^IDLE_TIMEOUT_SECONDS=/d' /etc/engine.env && "
2037
+ f"echo 'IDLE_TIMEOUT_SECONDS={seconds}' | sudo tee -a /etc/engine.env >/dev/null && "
2038
+ "sudo systemctl restart engine-idle-detector.timer"
2039
+ )
2040
+
2041
+ resp = ssm.send_command(
2042
+ InstanceIds=[engine["instance_id"]],
2043
+ DocumentName="AWS-RunShellScript",
2044
+ Parameters={"commands": [cmd], "executionTimeout": ["60"]},
2045
+ )
2046
+ cid = resp["Command"]["CommandId"]
2047
+ time.sleep(2)
2048
+ console.print(f"[green]✓ Idle timeout updated to {set}[/green]")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: dayhoff-tools
3
- Version: 1.3.16
3
+ Version: 1.3.17
4
4
  Summary: Common tools for all the repos at Dayhoff Labs
5
5
  Author: Daniel Martin-Alarcon
6
6
  Author-email: dma@dayhofflabs.com
@@ -3,7 +3,7 @@ dayhoff_tools/chemistry/standardizer.py,sha256=uMn7VwHnx02nc404eO6fRuS4rsl4dvSPf
3
3
  dayhoff_tools/chemistry/utils.py,sha256=jt-7JgF-GeeVC421acX-bobKbLU_X94KNOW24p_P-_M,2257
4
4
  dayhoff_tools/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
5
  dayhoff_tools/cli/cloud_commands.py,sha256=33qcWLmq-FwEXMdL3F0OHm-5Stlh2r65CldyEZgQ1no,40904
6
- dayhoff_tools/cli/engine_commands.py,sha256=TX9IwHkpb-x3OvvydwwhsXqxCpXnZ9TCNiOvYXYGP94,70265
6
+ dayhoff_tools/cli/engine_commands.py,sha256=DlWw8oUzOJqN6uUgsxF5whfY8jfwvBko8hvRm3ZHxVc,75814
7
7
  dayhoff_tools/cli/main.py,sha256=rgeEHD9lJ8SBCR34BTLb7gVInHUUdmEBNXAJnq5yEU4,4795
8
8
  dayhoff_tools/cli/swarm_commands.py,sha256=5EyKj8yietvT5lfoz8Zx0iQvVaNgc3SJX1z2zQR6o6M,5614
9
9
  dayhoff_tools/cli/utility_commands.py,sha256=qs8vH9TBFHsOPC3X8cU3qZigM3dDn-2Ytq4o_F2WubU,27874
@@ -27,7 +27,7 @@ dayhoff_tools/intake/uniprot.py,sha256=BZYJQF63OtPcBBnQ7_P9gulxzJtqyorgyuDiPeOJq
27
27
  dayhoff_tools/logs.py,sha256=DKdeP0k0kliRcilwvX0mUB2eipO5BdWUeHwh-VnsICs,838
28
28
  dayhoff_tools/sqlite.py,sha256=jV55ikF8VpTfeQqqlHSbY8OgfyfHj8zgHNpZjBLos_E,18672
29
29
  dayhoff_tools/warehouse.py,sha256=8YbnQ--usrEgDQGfvpV4MrMji55A0rq2hZaOgFGh6ag,15896
30
- dayhoff_tools-1.3.16.dist-info/METADATA,sha256=Ylw3uOqRFudCtgZdphUqKDLMBn0bH7O6-Ns8ZGTQ5R4,2825
31
- dayhoff_tools-1.3.16.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
32
- dayhoff_tools-1.3.16.dist-info/entry_points.txt,sha256=iAf4jteNqW3cJm6CO6czLxjW3vxYKsyGLZ8WGmxamSc,49
33
- dayhoff_tools-1.3.16.dist-info/RECORD,,
30
+ dayhoff_tools-1.3.17.dist-info/METADATA,sha256=69jNn8FqivgUWrwrLZ9S-ZEherpCtEHUrBABW5dewWs,2825
31
+ dayhoff_tools-1.3.17.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
32
+ dayhoff_tools-1.3.17.dist-info/entry_points.txt,sha256=iAf4jteNqW3cJm6CO6czLxjW3vxYKsyGLZ8WGmxamSc,49
33
+ dayhoff_tools-1.3.17.dist-info/RECORD,,