dofleet 0.1.0__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.
dofleet/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """dofleet: disposable DigitalOcean droplets with a cost guard."""
2
+
3
+ __version__ = "0.1.0"
dofleet/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
dofleet/api.py ADDED
@@ -0,0 +1,148 @@
1
+ """Thin DigitalOcean API v2 client: pagination, retries on 429/5xx, readable errors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any, Iterator
7
+
8
+ import httpx
9
+
10
+ API_BASE = "https://api.digitalocean.com/v2"
11
+ RETRY_STATUS = {429, 500, 502, 503, 504}
12
+
13
+
14
+ class ApiError(Exception):
15
+ def __init__(self, status: int, message: str, error_id: str = ""):
16
+ super().__init__(f"HTTP {status}: {message}")
17
+ self.status = status
18
+ self.message = message
19
+ self.error_id = error_id
20
+
21
+
22
+ class DOClient:
23
+ def __init__(self, token: str, *, base: str = API_BASE, transport: httpx.BaseTransport | None = None,
24
+ retries: int = 4, sleep=time.sleep):
25
+ self._http = httpx.Client(
26
+ base_url=base,
27
+ headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json",
28
+ "User-Agent": "dofleet"},
29
+ timeout=30,
30
+ transport=transport,
31
+ )
32
+ self._retries = retries
33
+ self._sleep = sleep
34
+
35
+ def close(self) -> None:
36
+ self._http.close()
37
+
38
+ # ---- low level -------------------------------------------------------
39
+ def request(self, method: str, path: str, **kw) -> dict[str, Any]:
40
+ for attempt in range(self._retries + 1):
41
+ resp = self._http.request(method, path, **kw)
42
+ # A POST that got a 5xx may still have created droplets; only 429 (not processed) is safe to resend.
43
+ retryable = RETRY_STATUS if method.upper() in ("GET", "DELETE") else {429}
44
+ if resp.status_code in retryable and attempt < self._retries:
45
+ self._sleep(self._retry_delay(resp, attempt))
46
+ continue
47
+ break
48
+ if resp.status_code >= 400:
49
+ try:
50
+ body = resp.json()
51
+ except ValueError:
52
+ body = {}
53
+ raise ApiError(resp.status_code, body.get("message") or resp.reason_phrase, body.get("id", ""))
54
+ if resp.status_code == 204 or not resp.content:
55
+ return {}
56
+ return resp.json()
57
+
58
+ @staticmethod
59
+ def _retry_delay(resp: httpx.Response, attempt: int) -> float:
60
+ reset = resp.headers.get("ratelimit-reset")
61
+ if resp.status_code == 429 and reset and reset.isdigit():
62
+ return max(1.0, min(60.0, int(reset) - time.time()))
63
+ return min(30.0, 2.0 ** attempt)
64
+
65
+ def paginate(self, path: str, key: str, params: dict | None = None) -> Iterator[dict]:
66
+ params = {"per_page": 200, **(params or {})}
67
+ page = 1
68
+ while True:
69
+ data = self.request("GET", path, params={**params, "page": page})
70
+ yield from data.get(key, [])
71
+ if not (data.get("links") or {}).get("pages", {}).get("next"):
72
+ return
73
+ page += 1
74
+
75
+ # ---- resources -------------------------------------------------------
76
+ def account(self) -> dict:
77
+ return self.request("GET", "/account").get("account", {})
78
+
79
+ def balance(self) -> dict:
80
+ return self.request("GET", "/customers/my/balance")
81
+
82
+ def sizes(self) -> list[dict]:
83
+ return list(self.paginate("/sizes", "sizes"))
84
+
85
+ def regions(self) -> list[dict]:
86
+ return list(self.paginate("/regions", "regions"))
87
+
88
+ def ssh_keys(self) -> list[dict]:
89
+ return list(self.paginate("/account/keys", "ssh_keys"))
90
+
91
+ def create_ssh_key(self, name: str, public_key: str) -> dict:
92
+ return self.request("POST", "/account/keys", json={"name": name, "public_key": public_key}).get("ssh_key", {})
93
+
94
+ def delete_ssh_key(self, key_id: int) -> None:
95
+ self.request("DELETE", f"/account/keys/{key_id}")
96
+
97
+ def droplets(self, tag: str | None = None) -> list[dict]:
98
+ return list(self.paginate("/droplets", "droplets", {"tag_name": tag} if tag else None))
99
+
100
+ def droplet(self, droplet_id: int) -> dict:
101
+ return self.request("GET", f"/droplets/{droplet_id}").get("droplet", {})
102
+
103
+ def create_droplets(self, body: dict) -> list[dict]:
104
+ data = self.request("POST", "/droplets", json=body)
105
+ if "droplets" in data:
106
+ return data["droplets"]
107
+ return [data["droplet"]] if "droplet" in data else []
108
+
109
+ def delete_droplet(self, droplet_id: int) -> None:
110
+ self.request("DELETE", f"/droplets/{droplet_id}")
111
+
112
+ def volumes(self) -> list[dict]:
113
+ return list(self.paginate("/volumes", "volumes"))
114
+
115
+ def create_volume(self, name: str, region: str, size_gb: int, tags: list[str]) -> dict:
116
+ return self.request("POST", "/volumes", json={"name": name, "region": region, "size_gigabytes": size_gb,
117
+ "tags": tags, "filesystem_type": "ext4"}).get("volume", {})
118
+
119
+ def delete_volume(self, volume_id: str) -> None:
120
+ self.request("DELETE", f"/volumes/{volume_id}")
121
+
122
+ def destroy_with_volumes(self, droplet_id: int, volume_ids: list[str]) -> None:
123
+ """Delete the droplet and exactly these attached volumes in one call (snapshots/backups untouched)."""
124
+ self.request("DELETE", f"/droplets/{droplet_id}/destroy_with_associated_resources/selective",
125
+ json={"volumes": volume_ids})
126
+
127
+ def droplet_action(self, droplet_id: int, action: str) -> dict:
128
+ return self.request("POST", f"/droplets/{droplet_id}/actions", json={"type": action}).get("action", {})
129
+
130
+ def tag_resource(self, tag: str, droplet_id, kind: str = "droplet") -> None:
131
+ try:
132
+ self.request("POST", "/tags", json={"name": tag})
133
+ except ApiError as e:
134
+ if e.status != 422: # 422 = tag already exists, which is fine
135
+ raise
136
+ self.request("POST", f"/tags/{tag}/resources",
137
+ json={"resources": [{"resource_id": str(droplet_id), "resource_type": kind}]})
138
+
139
+ def untag_resource(self, tag: str, droplet_id, kind: str = "droplet") -> None:
140
+ self.request("DELETE", f"/tags/{tag}/resources",
141
+ json={"resources": [{"resource_id": str(droplet_id), "resource_type": kind}]})
142
+
143
+
144
+ def public_ipv4(droplet: dict) -> str | None:
145
+ for net in (droplet.get("networks") or {}).get("v4", []):
146
+ if net.get("type") == "public":
147
+ return net.get("ip_address")
148
+ return None
dofleet/bake.py ADDED
@@ -0,0 +1,65 @@
1
+ """Snapshots of a finished setup, so later boots skip the slow apt work.
2
+
3
+ `dofleet bake web-01` snapshots the droplet as `dofleet-<preset>-<unix time>` and keeps only the newest
4
+ `bake_keep` snapshots per preset (snapshots bill per GB per month). `dofleet up <preset> --baked` boots from the newest
5
+ one; the setup template is skipped because it already ran, only the volume mount step is kept."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+
11
+ from . import fleet
12
+ from .api import DOClient
13
+ from .config import ConfigError
14
+
15
+ PREFIX = "dofleet-"
16
+
17
+
18
+ def preset_of(droplet: dict) -> str | None:
19
+ for tag in droplet.get("tags", []):
20
+ if tag.startswith(fleet.PRESET_PREFIX):
21
+ return tag[len(fleet.PRESET_PREFIX):]
22
+ return None
23
+
24
+
25
+ def snapshots(client: DOClient, preset: str | None = None) -> list[dict]:
26
+ """Newest first. preset=None -> every dofleet snapshot."""
27
+ out = []
28
+ for s in client.paginate("/snapshots", "snapshots", {"resource_type": "droplet"}):
29
+ name = s.get("name", "")
30
+ if not name.startswith(PREFIX):
31
+ continue
32
+ body, _, stamp = name[len(PREFIX):].rpartition("-")
33
+ if not stamp.isdigit() or (preset is not None and body != fleet.tag_safe(preset)):
34
+ continue
35
+ out.append({**s, "preset": body, "stamp": int(stamp)})
36
+ return sorted(out, key=lambda s: -s["stamp"])
37
+
38
+
39
+ def latest_image(client: DOClient, preset: str, region: str) -> int:
40
+ for s in snapshots(client, preset):
41
+ if region in s.get("regions", []):
42
+ return int(s["id"])
43
+ raise ConfigError("err.no_bake", preset=preset, region=region)
44
+
45
+
46
+ def bake(client: DOClient, droplet: dict, keep: int, *, now: float | None = None,
47
+ sleep=None, timeout_s: int = 1800) -> dict:
48
+ sleep = sleep or time.sleep
49
+ preset = preset_of(droplet) or fleet.tag_safe(droplet["name"])
50
+ name = f"{PREFIX}{fleet.tag_safe(preset)}-{int(now or time.time())}"
51
+ action = client.request("POST", f"/droplets/{droplet['id']}/actions", json={"type": "snapshot", "name": name})["action"]
52
+ waited = 0
53
+ while action.get("status") == "in-progress":
54
+ if waited >= timeout_s:
55
+ raise ConfigError("err.bake_timeout", name=name)
56
+ sleep(10)
57
+ waited += 10
58
+ action = client.request("GET", f"/actions/{action['id']}")["action"]
59
+ if action.get("status") != "completed":
60
+ raise ConfigError("err.bake_failed", name=name, status=action.get("status"))
61
+ removed = []
62
+ for old in snapshots(client, preset)[max(1, keep):]:
63
+ client.request("DELETE", f"/snapshots/{old['id']}")
64
+ removed.append(old["name"])
65
+ return {"snapshot": name, "preset": preset, "removed": removed}
dofleet/budget.py ADDED
@@ -0,0 +1,73 @@
1
+ """Monthly spend ceiling. `budget_usd` in [defaults] (0 = off).
2
+
3
+ Two guards, both based on DigitalOcean's own month-to-date usage figure:
4
+ - before creating: refuse when usage so far + what the new batch would cost until its timer (or a full month without one)
5
+ would pass the budget;
6
+ - in `reap`: once usage so far has passed the budget, `budget_action = "reap"` deletes every dofleet droplet
7
+ (with its volumes); "warn" only reports."""
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+
13
+ from .api import DOClient
14
+ from .config import ConfigError, Settings
15
+
16
+
17
+ @dataclass
18
+ class Status:
19
+ budget: float
20
+ used: float
21
+ committed: float = 0.0 # what running droplets will still cost until their timers (or month end)
22
+
23
+ @property
24
+ def on(self) -> bool:
25
+ return self.budget > 0
26
+
27
+ @property
28
+ def over(self) -> bool:
29
+ return self.on and self.used >= self.budget
30
+
31
+ @property
32
+ def left(self) -> float:
33
+ return max(0.0, self.budget - self.used - self.committed)
34
+
35
+
36
+ def committed(droplets: list[dict], now: float) -> float:
37
+ """Remaining cost of running droplets: until their expiry timer, or until month end without one."""
38
+ import calendar
39
+ from datetime import datetime, timezone
40
+ from . import fleet
41
+ d = datetime.fromtimestamp(now, timezone.utc)
42
+ month_end = datetime(d.year, d.month, calendar.monthrange(d.year, d.month)[1], 23, 59, tzinfo=timezone.utc).timestamp()
43
+ total = 0.0
44
+ for x in droplets:
45
+ hourly, monthly = fleet.prices(x)
46
+ until = min(fleet.expires_at(x) or month_end, month_end)
47
+ hours_left = max(0.0, until - now) / 3600
48
+ already = max(0.0, now - fleet.created_ts(x)) / 3600 * hourly
49
+ total += max(0.0, min(hours_left * hourly, (monthly or 1e12) - already))
50
+ return total
51
+
52
+
53
+ def status(client: DOClient, settings: Settings, now: float | None = None) -> Status:
54
+ import time
55
+ budget = float(settings.defaults.get("budget_usd") or 0)
56
+ if budget <= 0:
57
+ return Status(0.0, 0.0)
58
+ return Status(budget, float(client.balance().get("month_to_date_usage") or 0),
59
+ committed(client.droplets(), now or time.time()))
60
+
61
+
62
+ def check_new(st: Status, extra_cost: float) -> None:
63
+ if st.on and st.used + st.committed + extra_cost > st.budget:
64
+ raise ConfigError("err.budget", used=_usd(st.used + st.committed), extra=_usd(extra_cost), budget=_usd(st.budget))
65
+
66
+
67
+ def _usd(x: float) -> str:
68
+ return f"{x:.2f}" if x >= 0.01 or x == 0 else f"{x:.4f}"
69
+
70
+
71
+ def action(settings: Settings) -> str:
72
+ a = str(settings.defaults.get("budget_action") or "reap").lower()
73
+ return a if a in ("reap", "warn") else "reap"
dofleet/cli.py ADDED
@@ -0,0 +1,365 @@
1
+ """Command line. `dofleet` with no arguments in a terminal opens the menu."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import sys
8
+ import time
9
+ from typing import Optional
10
+
11
+ import typer
12
+ from rich.console import Console
13
+ from rich.markup import escape
14
+ from rich.table import Table
15
+
16
+ from . import __version__, budget, cloudinit, config, fleet, launch, ops, volumes
17
+ from .api import ApiError, DOClient
18
+ from .i18n import set_lang, t, resolve
19
+
20
+ app = typer.Typer(add_completion=False, no_args_is_help=False, rich_markup_mode=None, pretty_exceptions_enable=False,
21
+ help="Disposable DigitalOcean droplets with a cost guard.")
22
+ con = Console()
23
+ err = Console(stderr=True)
24
+
25
+
26
+ class State:
27
+ profile: Optional[str] = None
28
+ as_json = False
29
+ settings: Optional[config.Settings] = None
30
+ _client: Optional[DOClient] = None
31
+
32
+ def client(self) -> DOClient:
33
+ if self._client is None:
34
+ token, _ = self.settings.token(self.profile)
35
+ self._client = DOClient(token)
36
+ return self._client
37
+
38
+
39
+ S = State()
40
+
41
+
42
+ def out_json(data) -> None:
43
+ con.print_json(json.dumps(data, default=str))
44
+
45
+
46
+ def say(text: str) -> None:
47
+ """Human text; silent in --json mode so stdout stays valid JSON."""
48
+ if not S.as_json:
49
+ con.print(text)
50
+
51
+
52
+ def money(x: float) -> str:
53
+ return "<$0.01" if 0 < x < 0.005 else f"${x:,.2f}"
54
+
55
+
56
+ def confirm(prompt: str, assume: bool) -> bool:
57
+ if assume:
58
+ return True
59
+ if not sys.stdin.isatty():
60
+ err.print(t("err.need_yes"))
61
+ raise typer.Exit(2)
62
+ return typer.confirm(prompt, default=False)
63
+
64
+
65
+ @app.callback(invoke_without_command=True)
66
+ def root(ctx: typer.Context,
67
+ profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Account profile from config.toml"),
68
+ lang: Optional[str] = typer.Option(None, "--lang", help="en | ms"),
69
+ as_json: bool = typer.Option(False, "--json", help="Machine-readable output"),
70
+ version: bool = typer.Option(False, "--version")):
71
+ S.settings = config.load()
72
+ set_lang(resolve(lang, S.settings.defaults.get("lang")))
73
+ S.profile, S.as_json = profile, as_json
74
+ for w in S.settings.warnings:
75
+ err.print(f"[yellow]{t(w, path=S.settings.path)}[/]")
76
+ if version:
77
+ con.print(f"dofleet {__version__}")
78
+ raise typer.Exit()
79
+ if ctx.invoked_subcommand is None:
80
+ if sys.stdin.isatty() and not as_json:
81
+ from .menu import run_menu
82
+ run_menu(sys.modules[__name__])
83
+ else:
84
+ con.print(ctx.get_help())
85
+
86
+
87
+ @app.command("up", help="Create droplets from a preset")
88
+ def up(preset: Optional[str] = typer.Argument(None),
89
+ name: Optional[str] = typer.Option(None, "--name", "-n", help="Name or prefix"),
90
+ count: int = typer.Option(1, "--count", "-c"),
91
+ ttl: Optional[str] = typer.Option(None, "--ttl", help="Expiry timer, e.g. 30m 2h 3d. Empty string = none"),
92
+ keep: bool = typer.Option(False, "--keep", help="No expiry timer"),
93
+ region: list[str] = typer.Option([], "--region", "-r"),
94
+ size: list[str] = typer.Option([], "--size", "-s"),
95
+ image: Optional[str] = typer.Option(None, "--image"),
96
+ tag: list[str] = typer.Option([], "--tag"),
97
+ var: list[str] = typer.Option([], "--var", help="Template value, key=value"),
98
+ volume: list[int] = typer.Option([], "--volume", help="Add a block storage volume of this many GB (repeatable)"),
99
+ yes: bool = typer.Option(False, "--yes", "-y"),
100
+ baked: bool = typer.Option(False, "--baked", help="Boot from the newest `dofleet bake` snapshot of this preset"),
101
+ dry_run: bool = typer.Option(False, "--dry-run"),
102
+ no_wait: bool = typer.Option(False, "--no-wait")):
103
+ preset = preset or S.settings.defaults.get("preset", "quick")
104
+ ov = ops.Overrides(region, size, image, "" if keep else ttl, tag, dict(_kv(v) for v in var), volume, baked)
105
+ client = S.client()
106
+ with con.status(t("up.planning")):
107
+ plan = ops.plan_up(client, S.settings, preset, name, count, ov)
108
+ show_plan(plan)
109
+ if dry_run:
110
+ if S.as_json:
111
+ out_json({**_plan_dict(plan), "user_data": plan.user_data})
112
+ return
113
+ if not confirm(t("up.confirm", n=len(plan.names)), yes):
114
+ raise typer.Exit(1)
115
+ limit = float(S.settings.defaults.get("confirm_over_usd", 50))
116
+ if plan.cost_month > limit and not yes:
117
+ typed = typer.prompt(t("up.big_confirm", total=money(plan.cost_month), limit=money(limit)), default="")
118
+ if typed.strip() != str(len(plan.names)):
119
+ raise typer.Exit(1)
120
+ port = int(plan.preset.get("ready_port", 22))
121
+ with con.status(t("up.waiting", port=port)) as st:
122
+ res = launch.create_and_wait(client, S.settings, plan, wait=not no_wait, on_update=lambda s: st.update(
123
+ t("up.progress", ready=sum(v == "ready" for v in s.values()), total=len(s), port=port)))
124
+ _finish(plan, res)
125
+
126
+
127
+ def _kv(text: str) -> tuple[str, str]:
128
+ if "=" not in text:
129
+ raise typer.BadParameter(text)
130
+ k, v = text.split("=", 1)
131
+ return k.strip(), v.strip()
132
+
133
+
134
+ def _plan_dict(plan: ops.Plan) -> dict:
135
+ return {"preset": plan.preset["name"], "region": plan.region, "size": plan.size["slug"], "fallback": plan.fell_back,
136
+ "names": plan.names, "image": plan.image, "ttl_s": plan.ttl_s, "ssh_keys": len(plan.ssh_key_ids),
137
+ "cost_until_expiry_usd": round(plan.cost_ttl, 2), "cost_month_usd": round(plan.cost_month, 2)}
138
+
139
+
140
+ def _tilde(path: str) -> str:
141
+ home = os.path.expanduser("~")
142
+ return "~" + path[len(home):] if path.startswith(home + os.sep) else path
143
+
144
+
145
+ def show_plan(plan: ops.Plan) -> None:
146
+ if S.as_json:
147
+ return
148
+ s = plan.size
149
+ tb = Table(show_header=False, box=None, pad_edge=False)
150
+ tb.add_row(t("plan.preset"), plan.preset["name"])
151
+ tb.add_row(t("plan.where"), f"{plan.region} {s['slug']} ({s.get('vcpus')} vCPU / {fleet.mem_text(s.get('memory'))} / {s.get('disk')} GB)")
152
+ if plan.fell_back:
153
+ tb.add_row("", f"[yellow]{t('plan.fallback', want=f'{plan.regions_tried[0]} {plan.sizes_tried[0]}')}[/]")
154
+ tb.add_row(t("plan.names"), ", ".join(plan.names))
155
+ tb.add_row(t("plan.image"), plan.image)
156
+ if plan.ssh_key_ids:
157
+ tb.add_row(t("plan.keys"), str(len(plan.ssh_key_ids)))
158
+ elif plan.upload_key:
159
+ tb.add_row(t("plan.keys"), t("plan.upload_key", path=_tilde(plan.upload_key[0])))
160
+ else:
161
+ tb.add_row(t("plan.keys"), f"[yellow]{t('plan.no_keys')}[/]")
162
+ tb.add_row(t("plan.timer"), fleet.format_duration(plan.ttl_s) if plan.ttl_s else f"[yellow]{t('plan.no_timer')}[/]")
163
+ tb.add_row(t("plan.setup"), plan.preset.get("cloud_init") or "-")
164
+ if plan.preset.get("volumes"):
165
+ tb.add_row(t("plan.volumes"), t("plan.volumes_v", sizes=" + ".join(f"{g} GB" for g in volumes.sizes_gb(plan.preset))))
166
+ if plan.ttl_s:
167
+ tb.add_row(t("plan.cost"), t("plan.cost_ttl", ttl=money(plan.cost_ttl), month=money(plan.cost_month)))
168
+ else:
169
+ tb.add_row(t("plan.cost"), t("plan.cost_month", month=money(plan.cost_month)))
170
+ if plan.budget_left is not None:
171
+ tb.add_row(t("plan.budget"), t("plan.budget_v", left=money(plan.budget_left)))
172
+ con.print(tb)
173
+
174
+
175
+ def _finish(plan: ops.Plan, res: dict[int, dict]) -> None:
176
+ user = (plan.preset.get("vars") or {}).get("user", cloudinit.DEFAULT_VARS["user"]) if plan.user_data else "root"
177
+ items = [{"id": i, "name": r["droplet"].get("name"), "ip": r["ip"], "state": r["state"]} for i, r in res.items()]
178
+ if S.as_json:
179
+ out_json({**_plan_dict(plan), "droplets": items, "generated": plan.generated})
180
+ return
181
+ tb = Table(t("col.name"), "IP", t("col.state"), t("col.connect"))
182
+ for it in items:
183
+ conn = f"ssh {user}@{it['ip']}" if it["ip"] else "-"
184
+ if plan.preset.get("ready_port") and plan.preset.get("ready_port") != 22 and it["ip"]:
185
+ conn = f"{it['ip']}:{plan.preset['ready_port']} / {conn}"
186
+ tb.add_row(it["name"] or str(it["id"]), it["ip"] or "-", t(f"state.{it['state']}"), conn)
187
+ con.print(tb)
188
+ if any(it["state"] == "setup_failed" for it in items):
189
+ con.print(f"[red]{t('up.setup_failed', user='root')}[/]")
190
+ if plan.generated.get("password"):
191
+ con.print(f"[bold]{t('up.password', user=user, pw=plan.generated['password'])}[/]")
192
+ if plan.ttl_s:
193
+ con.print(t("up.expiry_note", ttl=fleet.format_duration(plan.ttl_s)))
194
+
195
+
196
+ @app.command("ls", help="List droplets with cost so far and time left")
197
+ def ls(managed: bool = typer.Option(False, "--managed", "-m", help="Only droplets made by dofleet")):
198
+ now = time.time()
199
+ data = ops.rows(S.client().droplets(fleet.MARK_TAG if managed else None), now)
200
+ if S.as_json:
201
+ out_json(data)
202
+ return
203
+ if not data:
204
+ con.print(t("ls.empty"))
205
+ return
206
+ tb = Table(t("col.name"), "IP", t("col.region"), t("col.size"), t("col.status"), t("col.age"),
207
+ t("col.spent"), t("col.monthly"), t("col.expires"))
208
+ for r in data:
209
+ exp = "-" if r["expires_in_s"] is None else (
210
+ f"[red]{t('ls.expired')}[/]" if r["expires_in_s"] <= 0 else fleet.format_duration(r["expires_in_s"]))
211
+ tb.add_row(r["name"], r["ip"] or "-", r["region"], r["size"], r["status"], fleet.format_duration(r["age_s"]),
212
+ money(r["spent_usd"]), money(r["monthly_usd"]), exp)
213
+ con.print(tb)
214
+ total = sum(r["monthly_usd"] for r in data)
215
+ con.print(t("ls.total", n=len(data), month=money(total), spent=money(sum(r["spent_usd"] for r in data))))
216
+
217
+
218
+ def _pick(patterns: list[str], any_glob: bool = True) -> list[dict]:
219
+ hits = fleet.match(S.client().droplets(), patterns)
220
+ if not any_glob: # a pattern like '*' must not sweep up droplets dofleet did not make
221
+ exact = {str(d["id"]) for d in hits} | {d["name"] for d in hits}
222
+ named = {p for p in patterns if p in exact}
223
+ skipped = [d for d in hits if not fleet.is_managed(d) and d["name"] not in named and str(d["id"]) not in named]
224
+ if skipped:
225
+ err.print(f"[yellow]{t('down.skipped', names=', '.join(d['name'] for d in skipped))}[/]")
226
+ hits = [d for d in hits if d not in skipped]
227
+ if not hits:
228
+ err.print(t("err.no_match", p=" ".join(patterns)))
229
+ raise typer.Exit(1)
230
+ return hits
231
+
232
+
233
+ @app.command("down", help="Delete droplets by name, id or glob (web-*)")
234
+ def down(patterns: list[str] = typer.Argument(...), yes: bool = typer.Option(False, "--yes", "-y"),
235
+ any_droplet: bool = typer.Option(False, "--any", help="Let patterns match droplets dofleet did not create"),
236
+ missing_ok: bool = typer.Option(False, "--missing-ok", help="Exit 0 when nothing matches (already gone)")):
237
+ if missing_ok and not fleet.match(S.client().droplets(), patterns):
238
+ if S.as_json:
239
+ out_json({"deleted": []})
240
+ return
241
+ hits = _pick(patterns, any_droplet)
242
+ say(t("down.list", names=", ".join(d["name"] for d in hits)))
243
+ if not confirm(t("down.confirm", n=len(hits)), yes):
244
+ raise typer.Exit(1)
245
+ owned = _owned_volumes(hits)
246
+ for d in hits:
247
+ volumes.destroy(S.client(), d, owned)
248
+ if S.as_json:
249
+ out_json({"deleted": [d["id"] for d in hits]})
250
+ else:
251
+ con.print(t("down.done", n=len(hits)))
252
+ if any(d.get("volume_ids") for d in hits):
253
+ con.print(t("down.volumes_async"))
254
+
255
+
256
+ @app.command("reap", help="Delete dofleet droplets whose timer ran out (safe to run from cron)")
257
+ def reap(yes: bool = typer.Option(False, "--yes", "-y"), dry_run: bool = typer.Option(False, "--dry-run")):
258
+ now = time.time()
259
+ victims = ops.reap_list(S.client(), S.settings, now)
260
+ st = budget.status(S.client(), S.settings)
261
+ if st.over:
262
+ err.print(f"[red]{t('reap.over_budget', used=money(st.used), budget=money(st.budget))}[/]")
263
+ if budget.action(S.settings) == "reap":
264
+ seen = {d["id"] for d in victims}
265
+ victims += [d for d in S.client().droplets(fleet.MARK_TAG) if d["id"] not in seen and fleet.is_managed(d)]
266
+ orphans = ops.orphan_volumes(S.client(), now)
267
+ if orphans:
268
+ say(t("reap.orphans", names=", ".join(v["name"] for v in orphans)))
269
+ if not dry_run and confirm(t("reap.orphans_confirm", n=len(orphans)), yes):
270
+ volumes.cleanup(S.client(), [v["id"] for v in orphans])
271
+ if S.as_json and (dry_run or not victims):
272
+ out_json({"expired": [d["id"] for d in victims], "deleted": []})
273
+ return
274
+ if not victims:
275
+ con.print(t("reap.none"))
276
+ return
277
+ say(t("reap.list", names=", ".join(d["name"] for d in victims)))
278
+ if dry_run or not confirm(t("down.confirm", n=len(victims)), yes):
279
+ return
280
+ deleted, failed = [], []
281
+ owned = _owned_volumes(victims)
282
+ budget_kill = st.over and budget.action(S.settings) == "reap"
283
+ grace = ops.reap_grace(S.settings)
284
+ for d in victims: # one failure must not stop the rest
285
+ if not budget_kill and not ops.still_expired(S.client(), d, time.time(), grace):
286
+ continue # extended since the list was taken
287
+ try:
288
+ volumes.destroy(S.client(), d, owned)
289
+ deleted.append(d)
290
+ except ApiError as e:
291
+ (deleted if e.status == 404 else failed).append(d) # 404 = someone else already deleted it
292
+ if deleted:
293
+ _notify(t("reap.notify", n=len(deleted), names=", ".join(d["name"] for d in deleted)))
294
+ if S.as_json:
295
+ out_json({"expired": [d["id"] for d in victims], "deleted": [d["id"] for d in deleted],
296
+ "failed": [d["id"] for d in failed]})
297
+ else:
298
+ con.print(t("down.done", n=len(deleted)))
299
+ if failed:
300
+ err.print(f"[red]{t('reap.failed', names=', '.join(d['name'] for d in failed))}[/]")
301
+ if failed:
302
+ raise typer.Exit(1)
303
+
304
+
305
+ def _owned_volumes(droplets: list[dict]) -> set[str]:
306
+ if not any(d.get("volume_ids") for d in droplets):
307
+ return set()
308
+ return {v["id"] for v in S.client().volumes() if fleet.MARK_TAG in (v.get("tags") or [])}
309
+
310
+
311
+ def _notify(message: str) -> None:
312
+ cmd = S.settings.defaults.get("notify_cmd") or []
313
+ if isinstance(cmd, str):
314
+ cmd = [cmd]
315
+ if not cmd:
316
+ return
317
+ import subprocess
318
+ try:
319
+ subprocess.run([*cmd, message], timeout=30, check=False)
320
+ except (OSError, subprocess.TimeoutExpired) as e:
321
+ err.print(f"[yellow]{t('warn.notify', err=e)}[/]")
322
+
323
+
324
+ @app.command("extend", help="Push the expiry timer out, or remove it with --keep")
325
+ def extend(patterns: list[str] = typer.Argument(...), ttl: str = typer.Option("2h", "--ttl"),
326
+ keep: bool = typer.Option(False, "--keep")):
327
+ now = time.time()
328
+ ttl_s = None if keep else fleet.parse_duration(ttl)
329
+ done = []
330
+ hits = _pick(patterns, any_glob=False)
331
+ foreign = [d for d in hits if not fleet.is_managed(d)]
332
+ if foreign: # a timer on a droplet dofleet did not make would hand it to the reaper
333
+ err.print(f"[yellow]{t('extend.foreign', names=', '.join(d['name'] for d in foreign))}[/]")
334
+ for d in [d for d in hits if fleet.is_managed(d)]:
335
+ exp = ops.set_expiry(S.client(), d, ttl_s, now)
336
+ done.append({"id": d["id"], "name": d["name"], "expires_at": exp})
337
+ if not S.as_json:
338
+ con.print(t("extend.kept", name=d["name"]) if exp is None
339
+ else t("extend.done", name=d["name"], left=fleet.format_duration(exp - now)))
340
+ if S.as_json:
341
+ out_json(done)
342
+
343
+
344
+ def runjob_error():
345
+ from .runjob import JobError
346
+ return JobError
347
+
348
+
349
+ def main() -> None:
350
+ from . import cli_info, cli_jobs # noqa: F401 registers the remaining commands
351
+ try:
352
+ app()
353
+ except runjob_error() as e:
354
+ err.print(f"[red]{t(e.key, **e.kw)}[/]")
355
+ sys.exit(1)
356
+ except (config.ConfigError, cloudinit.TemplateError) as e:
357
+ err.print(f"[red]{escape(t(e.key, **e.kw))}[/]")
358
+ sys.exit(1)
359
+ except ApiError as e:
360
+ key = {401: "err.api_401", 403: "err.api_403", 429: "err.api_429"}.get(e.status, "err.api")
361
+ err.print(f"[red]{escape(t(key, status=e.status, msg=e.message))}[/]")
362
+ sys.exit(1)
363
+ except fleet.DurationError as e:
364
+ err.print(f"[red]{t('err.duration', text=e)}[/]")
365
+ sys.exit(2)