v6ctl 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.
v6ctl.py ADDED
@@ -0,0 +1,1288 @@
1
+ """
2
+ v6ctl — command-line interface for the v6Node cloud platform.
3
+
4
+ Install: pipx install v6ctl
5
+ Configure: v6ctl config set token <your-token>
6
+ Use: v6ctl nodes list
7
+
8
+ Docs: https://github.com/v6Node/v6ctl
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import functools
14
+ import json as _json
15
+ import os
16
+ import sys
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import click
21
+ import requests
22
+ from rich import box
23
+ from rich.console import Console
24
+ from rich.panel import Panel
25
+ from rich.pretty import Pretty
26
+ from rich.table import Table
27
+ from rich.text import Text
28
+
29
+ __version__ = "0.1.0"
30
+
31
+ DEFAULT_API_URL = "https://cloud.v6node.com/api/v1"
32
+
33
+ CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / "v6ctl"
34
+ CONFIG_FILE = CONFIG_DIR / "config.json"
35
+
36
+ WEBHOOK_EVENTS = [
37
+ "node.deployed",
38
+ "node.deploy_failed",
39
+ "node.deleted",
40
+ "node.rebuilt",
41
+ "node.rebuild_failed",
42
+ "snapshot.created",
43
+ "snapshot.create_failed",
44
+ "snapshot.rolled_back",
45
+ "snapshot.deleted",
46
+ ]
47
+
48
+ console = Console()
49
+ err_console = Console(stderr=True)
50
+
51
+
52
+ # ═══════════════════════════════════════════════════════════
53
+ # Config
54
+ # ═══════════════════════════════════════════════════════════
55
+
56
+
57
+ def load_config() -> dict:
58
+ """Config precedence: env vars > config file > defaults."""
59
+ cfg: dict[str, Any] = {"api_url": DEFAULT_API_URL}
60
+ if CONFIG_FILE.exists():
61
+ try:
62
+ cfg.update(_json.loads(CONFIG_FILE.read_text()))
63
+ except _json.JSONDecodeError:
64
+ pass
65
+
66
+ if tok := (os.environ.get("V6_TOKEN") or os.environ.get("API_TOKEN")):
67
+ cfg["token"] = tok
68
+ if url := (os.environ.get("V6_API_URL") or os.environ.get("API_URL")):
69
+ cfg["api_url"] = url
70
+
71
+ return cfg
72
+
73
+
74
+ def save_config(cfg: dict) -> None:
75
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
76
+ CONFIG_FILE.write_text(_json.dumps(cfg, indent=2) + "\n")
77
+ CONFIG_FILE.chmod(0o600)
78
+
79
+
80
+ # ═══════════════════════════════════════════════════════════
81
+ # API Client
82
+ # ═══════════════════════════════════════════════════════════
83
+
84
+
85
+ class V6Error(Exception):
86
+ def __init__(self, status: int, code: str, message: str):
87
+ self.status = status
88
+ self.code = code
89
+ self.message = message
90
+ super().__init__(f"[{code}] {message}")
91
+
92
+
93
+ class V6Client:
94
+ def __init__(self, base_url: str, token: str):
95
+ self.base_url = base_url.rstrip("/")
96
+ self.session = requests.Session()
97
+ self.session.headers.update(
98
+ {
99
+ "Authorization": f"Bearer {token}",
100
+ "Content-Type": "application/json",
101
+ "Accept": "application/json",
102
+ "User-Agent": f"v6ctl/{__version__}",
103
+ }
104
+ )
105
+
106
+ def _request(self, method: str, path: str, body: dict | None = None):
107
+ url = f"{self.base_url}/{path.lstrip('/')}"
108
+ try:
109
+ resp = self.session.request(
110
+ method, url, data=_json.dumps(body) if body else None, timeout=30
111
+ )
112
+ except requests.RequestException as e:
113
+ raise V6Error(0, "NETWORK_ERROR", str(e)) from e
114
+
115
+ if resp.status_code == 204:
116
+ return None
117
+
118
+ try:
119
+ data = resp.json()
120
+ except ValueError:
121
+ raise V6Error(resp.status_code, "BAD_RESPONSE", resp.text[:200])
122
+
123
+ if not resp.ok:
124
+ if isinstance(data, dict) and "error" in data:
125
+ raise V6Error(resp.status_code, data.get("code", "ERROR"), data["error"])
126
+ if isinstance(data, dict) and "message" in data and "errors" in data:
127
+ fields = data["errors"]
128
+ msg = "; ".join(f"{k}: {', '.join(v)}" for k, v in fields.items())
129
+ raise V6Error(resp.status_code, "VALIDATION_ERROR", msg)
130
+ raise V6Error(resp.status_code, "UNKNOWN", str(data)[:200])
131
+
132
+ if isinstance(data, dict) and "data" in data:
133
+ result = data["data"]
134
+ if "meta" in data:
135
+ result = {"items": result, "meta": data["meta"]}
136
+ return result
137
+ return data
138
+
139
+ def _get(self, path):
140
+ return self._request("GET", path)
141
+
142
+ def _post(self, path, body=None):
143
+ return self._request("POST", path, body)
144
+
145
+ def _patch(self, path, body=None):
146
+ return self._request("PATCH", path, body)
147
+
148
+ def _delete(self, path):
149
+ return self._request("DELETE", path)
150
+
151
+ # ── SSH Keys ─────────────────────────────────────────
152
+
153
+ def keys_list(self):
154
+ return self._get("keys")
155
+
156
+ def keys_create(self, description, pubkey):
157
+ return self._post("keys", {"description": description, "pubkey": pubkey})
158
+
159
+ def keys_delete(self, key_id):
160
+ return self._delete(f"keys/{key_id}")
161
+
162
+ # ── Nodes ────────────────────────────────────────────
163
+
164
+ def nodes_list(self):
165
+ return self._get("nodes")
166
+
167
+ def nodes_show(self, pay_id):
168
+ return self._get(f"nodes/{pay_id}")
169
+
170
+ def nodes_create(self, *, region_id, plan_id, key_id, hostname=None, template=None, flavor_id=None, additional_address=None):
171
+ body = {"region_id": region_id, "plan_id": plan_id, "key_id": key_id}
172
+ if hostname:
173
+ body["hostname"] = hostname
174
+ if template:
175
+ body["template"] = template
176
+ if flavor_id:
177
+ body["flavor_id"] = flavor_id
178
+ if additional_address:
179
+ body["additional_address"] = additional_address
180
+ return self._post("nodes", body)
181
+
182
+ def nodes_update(self, pay_id, *, hostname=None, description=None, key_id=None, project_id=None):
183
+ body: dict[str, Any] = {}
184
+ if hostname is not None:
185
+ body["hostname"] = hostname
186
+ if description is not None:
187
+ body["description"] = description
188
+ if key_id is not None:
189
+ body["key_id"] = key_id
190
+ if project_id is not None:
191
+ body["project_id"] = project_id
192
+ return self._patch(f"nodes/{pay_id}", body)
193
+
194
+ def nodes_delete(self, pay_id):
195
+ return self._delete(f"nodes/{pay_id}")
196
+
197
+ def nodes_power(self, pay_id, action):
198
+ return self._post(f"nodes/{pay_id}/{action}")
199
+
200
+ def nodes_status(self, pay_id):
201
+ return self._get(f"nodes/{pay_id}/status")
202
+
203
+ def nodes_rebuild(self, pay_id, *, template=None, flavor_id=None):
204
+ body: dict[str, Any] = {}
205
+ if template:
206
+ body["template"] = template
207
+ if flavor_id:
208
+ body["flavor_id"] = flavor_id
209
+ return self._post(f"nodes/{pay_id}/rebuild", body)
210
+
211
+ def nodes_password(self, pay_id):
212
+ return self._post(f"nodes/{pay_id}/password")
213
+
214
+ def nodes_addresses(self, pay_id):
215
+ return self._get(f"nodes/{pay_id}/addresses")
216
+
217
+ def nodes_stats(self, pay_id, timerange):
218
+ return self._get(f"nodes/{pay_id}/stats/{timerange}")
219
+
220
+ def nodes_activity(self, pay_id):
221
+ return self._get(f"nodes/{pay_id}/activity")
222
+
223
+ # ── Webhooks ─────────────────────────────────────────
224
+
225
+ def webhooks_list(self):
226
+ return self._get("webhooks")
227
+
228
+ def webhooks_create(self, url, events):
229
+ return self._post("webhooks", {"url": url, "events": events})
230
+
231
+ def webhooks_update(self, webhook_id, *, url=None, enabled=None, events=None):
232
+ body: dict[str, Any] = {}
233
+ if url is not None:
234
+ body["url"] = url
235
+ if enabled is not None:
236
+ body["enabled"] = enabled
237
+ if events is not None:
238
+ body["events"] = events
239
+ return self._patch(f"webhooks/{webhook_id}", body)
240
+
241
+ def webhooks_delete(self, webhook_id):
242
+ return self._delete(f"webhooks/{webhook_id}")
243
+
244
+ def webhooks_test(self, webhook_id):
245
+ return self._post(f"webhooks/{webhook_id}/test")
246
+
247
+ def webhooks_deliveries(self, webhook_id):
248
+ return self._get(f"webhooks/{webhook_id}/deliveries")
249
+
250
+ # ── Reference (read-only) ────────────────────────────
251
+
252
+ def plans(self):
253
+ return self._get("plans")
254
+
255
+ def regions(self):
256
+ return self._get("regions")
257
+
258
+ def templates(self):
259
+ return self._get("templates")
260
+
261
+
262
+ # ═══════════════════════════════════════════════════════════
263
+ # Output — Rich renderers with --json fallback
264
+ # ═══════════════════════════════════════════════════════════
265
+
266
+
267
+ STATUS_COLORS = {
268
+ "running": "green",
269
+ "stopped": "red",
270
+ "deploying": "yellow",
271
+ "deleting": "yellow",
272
+ "rebuilding": "yellow",
273
+ "queued": "yellow",
274
+ "locked": "red",
275
+ }
276
+
277
+
278
+ def _is_json() -> bool:
279
+ ctx = click.get_current_context(silent=True)
280
+ return bool(ctx and ctx.obj and ctx.obj.get("json"))
281
+
282
+
283
+ def _render(data: Any, renderer):
284
+ """Emit JSON if --json is set, otherwise invoke the Rich renderer."""
285
+ if _is_json():
286
+ click.echo(_json.dumps(data, indent=2, default=str))
287
+ else:
288
+ renderer(data)
289
+
290
+
291
+ def _format_status(s: str) -> Text:
292
+ return Text(s, style=f"bold {STATUS_COLORS.get(s, 'dim')}")
293
+
294
+
295
+ def _human_bytes(b) -> str:
296
+ try:
297
+ b = int(b)
298
+ except (ValueError, TypeError):
299
+ return str(b)
300
+ for unit in ("B", "KB", "MB", "GB", "TB"):
301
+ if abs(b) < 1024:
302
+ return f"{b:.1f} {unit}" if unit != "B" else f"{b} {unit}"
303
+ b /= 1024
304
+ return f"{b:.1f} PB"
305
+
306
+
307
+ def _human_uptime(seconds) -> str:
308
+ try:
309
+ s = int(seconds)
310
+ except (ValueError, TypeError):
311
+ return str(seconds)
312
+ days, s = divmod(s, 86400)
313
+ hours, s = divmod(s, 3600)
314
+ mins, _ = divmod(s, 60)
315
+ parts = []
316
+ if days:
317
+ parts.append(f"{days}d")
318
+ if hours:
319
+ parts.append(f"{hours}h")
320
+ parts.append(f"{mins}m")
321
+ return " ".join(parts)
322
+
323
+
324
+ def _short_date(dt) -> str:
325
+ return dt[:10] if dt and len(dt) >= 10 else (dt or "")
326
+
327
+
328
+ def print_success(msg: str):
329
+ console.print(f"[bold green]✓[/bold green] {msg}")
330
+
331
+
332
+ def print_error(msg: str):
333
+ err_console.print(f"[bold red]✗[/bold red] {msg}")
334
+
335
+
336
+ def print_raw(data):
337
+ _render(data, lambda d: console.print(Pretty(d)))
338
+
339
+
340
+ # ── Keys ─────────────────────────────────────────────────
341
+
342
+
343
+ def _print_keys(keys):
344
+ if not keys:
345
+ console.print("[dim]No SSH keys found.[/dim]")
346
+ return
347
+ t = Table(title="SSH Keys", box=box.ROUNDED)
348
+ t.add_column("ID", style="bold cyan", justify="right")
349
+ t.add_column("Description", style="white")
350
+ t.add_column("Created", style="dim")
351
+ for k in keys:
352
+ t.add_row(str(k["id"]), k.get("description", ""), k.get("created_at", ""))
353
+ console.print(t)
354
+
355
+
356
+ def _print_key(key):
357
+ console.print(
358
+ Panel(
359
+ f"[bold cyan]ID:[/bold cyan] {key['id']}\n"
360
+ f"[bold]Description:[/bold] {key.get('description', '')}\n"
361
+ f"[dim]Created:[/dim] {key.get('created_at', '')}",
362
+ title="SSH Key",
363
+ border_style="green",
364
+ box=box.ROUNDED,
365
+ )
366
+ )
367
+
368
+
369
+ # ── Nodes ────────────────────────────────────────────────
370
+
371
+
372
+ def _print_nodes(data):
373
+ items = data.get("items", data) if isinstance(data, dict) else data
374
+ meta = data.get("meta") if isinstance(data, dict) else None
375
+ if not items:
376
+ console.print("[dim]No nodes found.[/dim]")
377
+ return
378
+
379
+ t = Table(title="Nodes", box=box.ROUNDED, show_lines=True)
380
+ for col, style in [
381
+ ("ID", "bold cyan"),
382
+ ("Hostname", "white"),
383
+ ("Region", "dim"),
384
+ ("Plan", "dim"),
385
+ ("OS", "dim"),
386
+ ("IP", "green"),
387
+ ("Created", "dim"),
388
+ ]:
389
+ t.add_column(col, style=style, no_wrap=True)
390
+
391
+ for n in items:
392
+ region = n.get("region") or {}
393
+ plan = n.get("plan") or {}
394
+ region_str = region.get("title", "") if isinstance(region, dict) else str(region)
395
+ plan_str = plan.get("title", "") if isinstance(plan, dict) else str(plan)
396
+ addresses = n.get("addresses") or []
397
+ ip_str = addresses[0]["ip"] if addresses else ""
398
+ if len(addresses) > 1:
399
+ ip_str += f" [dim](+{len(addresses) - 1})[/dim]"
400
+ locked = " [red]LOCKED[/red]" if n.get("is_locked") else ""
401
+ t.add_row(
402
+ n.get("pay_id", ""),
403
+ (n.get("hostname") or "") + locked,
404
+ region_str,
405
+ plan_str,
406
+ n.get("template", ""),
407
+ ip_str,
408
+ _short_date(n.get("created_at", "")),
409
+ )
410
+ console.print(t)
411
+ if meta:
412
+ console.print(
413
+ f"[dim]Page {meta.get('current_page')} of {meta.get('last_page')} "
414
+ f"({meta.get('total')} total)[/dim]"
415
+ )
416
+
417
+
418
+ def _print_node(node, status=None, activity=None):
419
+ lines = []
420
+
421
+ def add(label, value, style="white"):
422
+ if value is not None and value != "":
423
+ lines.append(f"[bold]{label}:[/bold] [{style}]{value}[/{style}]")
424
+
425
+ add("Pay ID", node.get("pay_id"), "cyan")
426
+ add("Hostname", node.get("hostname"))
427
+ add("Description", node.get("description"))
428
+
429
+ region = node.get("region") or {}
430
+ add("Region", region.get("title") if isinstance(region, dict) else region)
431
+
432
+ plan = node.get("plan") or {}
433
+ if isinstance(plan, dict):
434
+ add(
435
+ "Plan",
436
+ f"{plan.get('title', '')} "
437
+ f"({plan.get('cores', '?')} cores, "
438
+ f"{plan.get('memory_mb', '?')} MB, "
439
+ f"{plan.get('disk_gb', '?')} GB)",
440
+ )
441
+ add("Template", node.get("template"))
442
+
443
+ flavor = node.get("flavor") or {}
444
+ if isinstance(flavor, dict) and flavor.get("title"):
445
+ add("Flavor", flavor.get("title"))
446
+
447
+ for a in node.get("addresses") or []:
448
+ primary = " (primary)" if a.get("primary") else ""
449
+ lines.append(
450
+ f"[bold]IP:[/bold] [green]{a['ip']}[/green] "
451
+ f"{a.get('type', '')}/{a.get('routing', '')}{primary}"
452
+ )
453
+
454
+ if node.get("is_locked"):
455
+ lines.append("[bold red]LOCKED[/bold red]")
456
+ if node.get("requires_reboot"):
457
+ lines.append("[bold yellow]REQUIRES REBOOT[/bold yellow]")
458
+
459
+ add("Created", node.get("created_at"), "dim")
460
+
461
+ console.print(
462
+ Panel(
463
+ "\n".join(lines),
464
+ title=f"Node {node.get('pay_id', '')}",
465
+ border_style="cyan",
466
+ box=box.ROUNDED,
467
+ )
468
+ )
469
+
470
+ if status and isinstance(status, dict):
471
+ _print_node_status(status)
472
+
473
+ if activity and isinstance(activity, list):
474
+ t = Table(title="Recent Activity", box=box.ROUNDED, border_style="dim")
475
+ t.add_column("Date", style="dim", no_wrap=True)
476
+ t.add_column("Subject", style="white")
477
+ t.add_column("Action", style="cyan")
478
+ for entry in activity[:5]:
479
+ t.add_row(
480
+ _short_date(entry.get("created_at", "")),
481
+ entry.get("subject", ""),
482
+ entry.get("description", ""),
483
+ )
484
+ console.print(t)
485
+
486
+
487
+ def _print_node_status(status):
488
+ mem = status.get("memory", {})
489
+ disk = status.get("disk", {})
490
+ try:
491
+ cpu_pct = f"{float(status.get('cpu', 0)) * 100:.1f}%"
492
+ except (ValueError, TypeError):
493
+ cpu_pct = str(status.get("cpu", "N/A"))
494
+
495
+ lines = [
496
+ f"[bold]State:[/bold] {_format_status(status.get('state', 'unknown'))}",
497
+ f"[bold]Uptime:[/bold] {_human_uptime(status.get('uptime', 'N/A'))}",
498
+ f"[bold]CPU:[/bold] {cpu_pct}",
499
+ f"[bold]Memory:[/bold] {_human_bytes(mem.get('used', '?'))} / {_human_bytes(mem.get('total', '?'))}",
500
+ f"[bold]Disk:[/bold] {_human_bytes(disk.get('used', '?'))} / {_human_bytes(disk.get('total', '?'))}",
501
+ ]
502
+ console.print(
503
+ Panel(
504
+ "\n".join(lines),
505
+ title="Node Status",
506
+ border_style="cyan",
507
+ box=box.ROUNDED,
508
+ )
509
+ )
510
+
511
+
512
+ def _print_addresses(addresses):
513
+ if not addresses:
514
+ console.print("[dim]No addresses found.[/dim]")
515
+ return
516
+ t = Table(title="IP Addresses", box=box.ROUNDED)
517
+ t.add_column("ID", style="bold", justify="right")
518
+ t.add_column("IP", style="green")
519
+ t.add_column("Type", style="dim")
520
+ t.add_column("Range", style="dim")
521
+ t.add_column("Primary", justify="center")
522
+ t.add_column("Routing", style="dim")
523
+ for a in addresses:
524
+ primary = "[green]Yes[/green]" if a.get("primary") else "[dim]No[/dim]"
525
+ t.add_row(
526
+ str(a["id"]),
527
+ a["ip"],
528
+ a.get("type", ""),
529
+ a.get("range", ""),
530
+ primary,
531
+ a.get("routing", ""),
532
+ )
533
+ console.print(t)
534
+
535
+
536
+ def _print_action(data, title="Action"):
537
+ lines = []
538
+ for k, v in (data or {}).items():
539
+ if k == "status":
540
+ lines.append(f"[bold]{k}:[/bold] {_format_status(str(v))}")
541
+ else:
542
+ lines.append(f"[bold]{k}:[/bold] {v}")
543
+ console.print(
544
+ Panel("\n".join(lines), title=title, border_style="yellow", box=box.ROUNDED)
545
+ )
546
+
547
+
548
+ def _print_password(password):
549
+ console.print(
550
+ Panel(
551
+ f"[bold yellow]{password}[/bold yellow]",
552
+ title="Root Password",
553
+ subtitle="[dim]Save this — it won't be shown again[/dim]",
554
+ border_style="yellow",
555
+ box=box.HEAVY,
556
+ )
557
+ )
558
+
559
+
560
+ # ── Webhooks ─────────────────────────────────────────────
561
+
562
+
563
+ def _print_webhooks(webhooks):
564
+ items = webhooks if isinstance(webhooks, list) else [webhooks]
565
+ if not items:
566
+ console.print("[dim]No webhooks found.[/dim]")
567
+ return
568
+ t = Table(title="Webhooks", box=box.ROUNDED)
569
+ t.add_column("ID", style="bold cyan", justify="right")
570
+ t.add_column("URL", style="white")
571
+ t.add_column("Events", style="dim")
572
+ t.add_column("Enabled", justify="center")
573
+ t.add_column("Approved", justify="center")
574
+ t.add_column("Created", style="dim")
575
+ for w in items:
576
+ events = w.get("events", "")
577
+ if isinstance(events, list):
578
+ events = ", ".join(events)
579
+ enabled = "[green]Yes[/green]" if w.get("enabled") in (True, "true", 1, "1") else "[red]No[/red]"
580
+ approved = "[green]Yes[/green]" if w.get("approved") in (True, "true", 1, "1") else "[yellow]Pending[/yellow]"
581
+ t.add_row(
582
+ str(w.get("id", "")),
583
+ str(w.get("url", "")),
584
+ str(events),
585
+ enabled,
586
+ approved,
587
+ str(w.get("created_at", "")),
588
+ )
589
+ console.print(t)
590
+
591
+
592
+ def _print_webhook(webhook):
593
+ events = webhook.get("events", "")
594
+ if isinstance(events, list):
595
+ events = ", ".join(events)
596
+ console.print(
597
+ Panel(
598
+ f"[bold cyan]ID:[/bold cyan] {webhook.get('id')}\n"
599
+ f"[bold]URL:[/bold] {webhook.get('url')}\n"
600
+ f"[bold]Events:[/bold] {events}\n"
601
+ f"[bold]Enabled:[/bold] {webhook.get('enabled')}\n"
602
+ f"[bold]Approved:[/bold] {webhook.get('approved')}\n"
603
+ f"[dim]Created:[/dim] {webhook.get('created_at', '')}",
604
+ title="Webhook",
605
+ border_style="cyan",
606
+ box=box.ROUNDED,
607
+ )
608
+ )
609
+
610
+
611
+ # ── Reference ────────────────────────────────────────────
612
+
613
+
614
+ def _print_plans(plans):
615
+ t = Table(title="Plans", box=box.ROUNDED)
616
+ t.add_column("ID", style="bold cyan", justify="right")
617
+ t.add_column("Name", style="white")
618
+ t.add_column("Cores", justify="right")
619
+ t.add_column("Memory", justify="right")
620
+ t.add_column("Disk", justify="right")
621
+ t.add_column("Traffic", justify="right")
622
+ t.add_column("Monthly", justify="right", style="green")
623
+ t.add_column("Annual", justify="right", style="dim")
624
+ for p in plans:
625
+ monthly = p.get("price_monthly")
626
+ annual = p.get("price_annual")
627
+ t.add_row(
628
+ str(p.get("id", "")),
629
+ p.get("title", ""),
630
+ str(p.get("cores", "")),
631
+ f"{p.get('memory_mb', 0)} MB",
632
+ f"{p.get('disk_gb', 0)} GB",
633
+ f"{p.get('traffic_gb', 0)} GB",
634
+ f"{monthly / 100:.2f}€" if monthly else "",
635
+ f"{annual / 100:.2f}€" if annual else "",
636
+ )
637
+ console.print(t)
638
+
639
+
640
+ def _print_regions(regions):
641
+ t = Table(title="Regions", box=box.ROUNDED)
642
+ t.add_column("ID", style="bold cyan", justify="right")
643
+ t.add_column("Name", style="white")
644
+ t.add_column("Available", justify="center")
645
+ t.add_column("Templates", style="dim")
646
+ for r in regions:
647
+ avail = "[green]Yes[/green]" if r.get("available") else "[red]No[/red]"
648
+ templates = ", ".join(r.get("templates", []))
649
+ t.add_row(str(r.get("id", "")), r.get("title", ""), avail, templates)
650
+ console.print(t)
651
+
652
+
653
+ def _print_templates(templates):
654
+ # Grouped shape: [{family, label, versions: [...]}]
655
+ if isinstance(templates, list) and templates and "versions" in templates[0]:
656
+ t = Table(title="OS Templates", box=box.ROUNDED)
657
+ t.add_column("Family", style="bold white")
658
+ t.add_column("ID", style="cyan", justify="right")
659
+ t.add_column("Slug", style="bold")
660
+ t.add_column("Title", style="white")
661
+ t.add_column("Version", style="dim")
662
+ t.add_column("LTS", justify="center")
663
+ for fam in templates:
664
+ for i, v in enumerate(fam.get("versions", [])):
665
+ lts = "[green]Yes[/green]" if v.get("lts") else "[dim]No[/dim]"
666
+ t.add_row(
667
+ fam.get("label", "") if i == 0 else "",
668
+ str(v.get("id", "")),
669
+ v.get("template", ""),
670
+ v.get("title", ""),
671
+ v.get("version", ""),
672
+ lts,
673
+ )
674
+ console.print(t)
675
+ elif isinstance(templates, list) and templates and isinstance(templates[0], dict):
676
+ t = Table(title="Templates", box=box.ROUNDED)
677
+ t.add_column("ID", style="bold cyan", justify="right")
678
+ t.add_column("Title", style="white")
679
+ t.add_column("Slug", style="dim")
680
+ for tpl in templates:
681
+ t.add_row(
682
+ str(tpl.get("id", "")),
683
+ tpl.get("title", ""),
684
+ tpl.get("slug", tpl.get("template", "")),
685
+ )
686
+ console.print(t)
687
+ else:
688
+ console.print(Pretty(templates))
689
+
690
+
691
+ # ═══════════════════════════════════════════════════════════
692
+ # Click CLI
693
+ # ═══════════════════════════════════════════════════════════
694
+
695
+
696
+ def handle_errors(fn):
697
+ @functools.wraps(fn)
698
+ def wrapper(*args, **kwargs):
699
+ try:
700
+ return fn(*args, **kwargs)
701
+ except V6Error as e:
702
+ if _is_json():
703
+ click.echo(
704
+ _json.dumps(
705
+ {"error": e.message, "code": e.code, "status": e.status}, indent=2
706
+ ),
707
+ err=True,
708
+ )
709
+ else:
710
+ print_error(f"{e.message} ({e.code})")
711
+ sys.exit(1)
712
+
713
+ return wrapper
714
+
715
+
716
+ def require_client(ctx):
717
+ """Ensure a configured client is present; error with guidance if not."""
718
+ client = ctx.obj.get("client")
719
+ if client is None:
720
+ print_error(
721
+ "No API token configured. Run: [bold]v6ctl config set token <your-token>[/bold]"
722
+ )
723
+ sys.exit(2)
724
+ return client
725
+
726
+
727
+ pass_client = click.make_pass_decorator(dict, ensure=True)
728
+
729
+
730
+ CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
731
+
732
+
733
+ @click.group(context_settings=CONTEXT_SETTINGS)
734
+ @click.option("--json", "output_json", is_flag=True, help="Output JSON instead of formatted tables.")
735
+ @click.version_option(__version__, "-V", "--version", prog_name="v6ctl")
736
+ @click.pass_context
737
+ def cli(ctx, output_json):
738
+ """v6ctl — manage v6Node cloud resources.
739
+
740
+ \b
741
+ Get started:
742
+ v6ctl config set token <your-token>
743
+ v6ctl nodes list
744
+
745
+ \b
746
+ Environment variables (override config file):
747
+ V6_TOKEN API token
748
+ V6_API_URL API base URL (default: {default_url})
749
+
750
+ Docs: https://github.com/v6Node/v6ctl
751
+ """
752
+ cfg = load_config()
753
+ ctx.ensure_object(dict)
754
+ ctx.obj["json"] = output_json
755
+ ctx.obj["config"] = cfg
756
+
757
+ # `config` subcommands don't need a live client
758
+ if ctx.invoked_subcommand == "config":
759
+ ctx.obj["client"] = None
760
+ return
761
+
762
+ token = cfg.get("token")
763
+ api_url = cfg.get("api_url", DEFAULT_API_URL)
764
+
765
+ if not token:
766
+ ctx.obj["client"] = None
767
+ else:
768
+ ctx.obj["client"] = V6Client(api_url, token)
769
+
770
+
771
+ cli.help = cli.help.format(default_url=DEFAULT_API_URL)
772
+
773
+
774
+ # ═══════════════════════════════════════════════════════════
775
+ # config
776
+ # ═══════════════════════════════════════════════════════════
777
+
778
+
779
+ @cli.group(invoke_without_command=True)
780
+ @click.pass_context
781
+ def config(ctx):
782
+ """Manage local configuration (token, API URL)."""
783
+ if ctx.invoked_subcommand is None:
784
+ ctx.invoke(config_show)
785
+
786
+
787
+ @config.command("set")
788
+ @click.argument("key", type=click.Choice(["token", "api_url"]))
789
+ @click.argument("value")
790
+ def config_set(key, value):
791
+ """Set a config value (token, api_url)."""
792
+ cfg = {}
793
+ if CONFIG_FILE.exists():
794
+ try:
795
+ cfg = _json.loads(CONFIG_FILE.read_text())
796
+ except _json.JSONDecodeError:
797
+ pass
798
+ cfg[key] = value
799
+ save_config(cfg)
800
+ print_success(f"Set [bold]{key}[/bold] → saved to {CONFIG_FILE}")
801
+
802
+
803
+ @config.command("unset")
804
+ @click.argument("key", type=click.Choice(["token", "api_url"]))
805
+ def config_unset(key):
806
+ """Remove a config value."""
807
+ if not CONFIG_FILE.exists():
808
+ print_error(f"No config file at {CONFIG_FILE}")
809
+ sys.exit(1)
810
+ cfg = _json.loads(CONFIG_FILE.read_text())
811
+ cfg.pop(key, None)
812
+ save_config(cfg)
813
+ print_success(f"Unset [bold]{key}[/bold]")
814
+
815
+
816
+ @config.command("show")
817
+ @click.pass_context
818
+ def config_show(ctx):
819
+ """Show resolved configuration."""
820
+ cfg = dict(ctx.obj["config"])
821
+ if tok := cfg.get("token"):
822
+ cfg["token"] = tok[:8] + "…" + tok[-4:] if len(tok) > 12 else "***"
823
+ if _is_json():
824
+ click.echo(_json.dumps(cfg, indent=2))
825
+ else:
826
+ console.print(
827
+ Panel(
828
+ "\n".join(f"[bold]{k}:[/bold] {v}" for k, v in cfg.items()) or "[dim]empty[/dim]",
829
+ title="v6ctl config",
830
+ subtitle=f"[dim]{CONFIG_FILE}[/dim]",
831
+ border_style="cyan",
832
+ box=box.ROUNDED,
833
+ )
834
+ )
835
+
836
+
837
+ @config.command("path")
838
+ def config_path():
839
+ """Print the path to the config file."""
840
+ click.echo(str(CONFIG_FILE))
841
+
842
+
843
+ # ═══════════════════════════════════════════════════════════
844
+ # keys
845
+ # ═══════════════════════════════════════════════════════════
846
+
847
+
848
+ @cli.group(invoke_without_command=True)
849
+ @click.pass_context
850
+ def keys(ctx):
851
+ """Manage SSH keys."""
852
+ if ctx.invoked_subcommand is None:
853
+ ctx.invoke(keys_list)
854
+
855
+
856
+ @keys.command("list")
857
+ @click.pass_context
858
+ @handle_errors
859
+ def keys_list(ctx):
860
+ """List all SSH keys."""
861
+ client = require_client(ctx)
862
+ _render(client.keys_list(), _print_keys)
863
+
864
+
865
+ @keys.command("create")
866
+ @click.option("-d", "--description", required=True, help="Label for this key.")
867
+ @click.option("-k", "--pubkey", required=True, help="SSH public key string.")
868
+ @click.pass_context
869
+ @handle_errors
870
+ def keys_create(ctx, description, pubkey):
871
+ """Add a new SSH key."""
872
+ client = require_client(ctx)
873
+ _render(client.keys_create(description, pubkey), _print_key)
874
+
875
+
876
+ @keys.command("delete")
877
+ @click.argument("key_id", type=int)
878
+ @click.option("-y", "--yes", is_flag=True, help="Skip confirmation.")
879
+ @click.pass_context
880
+ @handle_errors
881
+ def keys_delete(ctx, key_id, yes):
882
+ """Delete an SSH key by ID."""
883
+ client = require_client(ctx)
884
+ if not yes:
885
+ click.confirm(f"Delete SSH key {key_id}?", abort=True)
886
+ client.keys_delete(key_id)
887
+ print_success(f"Key {key_id} deleted.")
888
+
889
+
890
+ # ═══════════════════════════════════════════════════════════
891
+ # nodes
892
+ # ═══════════════════════════════════════════════════════════
893
+
894
+
895
+ class NodeGroup(click.Group):
896
+ """Route unknown positional args to `show` so `nodes <pay_id>` just works."""
897
+
898
+ def resolve_command(self, ctx, args):
899
+ try:
900
+ return super().resolve_command(ctx, args)
901
+ except click.UsageError:
902
+ if args and not args[0].startswith("-"):
903
+ return super().resolve_command(ctx, ["show"] + args)
904
+ raise
905
+
906
+
907
+ @cli.group(cls=NodeGroup, invoke_without_command=True)
908
+ @click.pass_context
909
+ def nodes(ctx):
910
+ """Manage VPS nodes."""
911
+ if ctx.invoked_subcommand is None:
912
+ ctx.invoke(nodes_list)
913
+
914
+
915
+ @nodes.command("list")
916
+ @click.pass_context
917
+ @handle_errors
918
+ def nodes_list(ctx):
919
+ """List all nodes."""
920
+ client = require_client(ctx)
921
+ _render(client.nodes_list(), _print_nodes)
922
+
923
+
924
+ @nodes.command("show")
925
+ @click.argument("pay_id")
926
+ @click.pass_context
927
+ @handle_errors
928
+ def nodes_show(ctx, pay_id):
929
+ """Show details for a node."""
930
+ client = require_client(ctx)
931
+ data = client.nodes_show(pay_id)
932
+
933
+ if _is_json() or not isinstance(data, dict):
934
+ _render(data, _print_node)
935
+ return
936
+
937
+ status = activity = None
938
+ try:
939
+ status = client.nodes_status(pay_id)
940
+ except V6Error:
941
+ pass
942
+ try:
943
+ activity = client.nodes_activity(pay_id)
944
+ except V6Error:
945
+ pass
946
+ _print_node(data, status=status, activity=activity)
947
+
948
+
949
+ @nodes.command("create")
950
+ @click.option("-r", "--region", "region_id", required=True, type=int, help="Region ID.")
951
+ @click.option("-p", "--plan", "plan_id", required=True, type=int, help="Plan ID.")
952
+ @click.option("-k", "--key", "key_id", required=True, type=int, help="SSH key ID.")
953
+ @click.option("-h", "--hostname", default=None, help="Custom hostname.")
954
+ @click.option("-t", "--template", default=None, help="Template slug (e.g. debian-13).")
955
+ @click.option("--flavor", "flavor_id", default=None, type=int, help="Flavor ID.")
956
+ @click.option(
957
+ "--address",
958
+ "additional_address",
959
+ default=None,
960
+ type=click.Choice(["shared_ipv4", "dedicated_ipv4"]),
961
+ help="Additional IP address type.",
962
+ )
963
+ @click.pass_context
964
+ @handle_errors
965
+ def nodes_create(ctx, region_id, plan_id, key_id, hostname, template, flavor_id, additional_address):
966
+ """Deploy a new node."""
967
+ client = require_client(ctx)
968
+ result = client.nodes_create(
969
+ region_id=region_id,
970
+ plan_id=plan_id,
971
+ key_id=key_id,
972
+ hostname=hostname,
973
+ template=template,
974
+ flavor_id=flavor_id,
975
+ additional_address=additional_address,
976
+ )
977
+ _render(result, lambda d: _print_action(d, title="Node Deploying"))
978
+
979
+
980
+ @nodes.command("update")
981
+ @click.argument("pay_id")
982
+ @click.option("--hostname", default=None, help="New hostname.")
983
+ @click.option("--description", default=None, help="New description.")
984
+ @click.option("--key", "key_id", default=None, type=int, help="New SSH key ID.")
985
+ @click.option("--project", "project_id", default=None, type=int, help="Project ID.")
986
+ @click.pass_context
987
+ @handle_errors
988
+ def nodes_update(ctx, pay_id, hostname, description, key_id, project_id):
989
+ """Update hostname, description, key, or project."""
990
+ client = require_client(ctx)
991
+ result = client.nodes_update(
992
+ pay_id,
993
+ hostname=hostname,
994
+ description=description,
995
+ key_id=key_id,
996
+ project_id=project_id,
997
+ )
998
+ if isinstance(result, dict):
999
+ _render(result, _print_node)
1000
+ else:
1001
+ print_raw(result)
1002
+
1003
+
1004
+ @nodes.command("delete")
1005
+ @click.argument("pay_id")
1006
+ @click.option("-y", "--yes", is_flag=True, help="Skip confirmation.")
1007
+ @click.pass_context
1008
+ @handle_errors
1009
+ def nodes_delete(ctx, pay_id, yes):
1010
+ """Destroy a node. Irreversible."""
1011
+ client = require_client(ctx)
1012
+ if not yes:
1013
+ click.confirm(f"Delete node {pay_id}? This is irreversible.", abort=True)
1014
+ _render(client.nodes_delete(pay_id), lambda d: _print_action(d, title="Node Deleting"))
1015
+
1016
+
1017
+ @nodes.command("start")
1018
+ @click.argument("pay_id")
1019
+ @click.pass_context
1020
+ @handle_errors
1021
+ def nodes_start(ctx, pay_id):
1022
+ """Start a stopped node."""
1023
+ client = require_client(ctx)
1024
+ _render(client.nodes_power(pay_id, "start"), lambda d: _print_action(d, title="Start Queued"))
1025
+
1026
+
1027
+ @nodes.command("stop")
1028
+ @click.argument("pay_id")
1029
+ @click.pass_context
1030
+ @handle_errors
1031
+ def nodes_stop(ctx, pay_id):
1032
+ """Hard stop a node (power off)."""
1033
+ client = require_client(ctx)
1034
+ _render(client.nodes_power(pay_id, "stop"), lambda d: _print_action(d, title="Stop Queued"))
1035
+
1036
+
1037
+ @nodes.command("shutdown")
1038
+ @click.argument("pay_id")
1039
+ @click.pass_context
1040
+ @handle_errors
1041
+ def nodes_shutdown(ctx, pay_id):
1042
+ """Graceful shutdown via ACPI."""
1043
+ client = require_client(ctx)
1044
+ _render(
1045
+ client.nodes_power(pay_id, "shutdown"),
1046
+ lambda d: _print_action(d, title="Shutdown Queued"),
1047
+ )
1048
+
1049
+
1050
+ @nodes.command("reboot")
1051
+ @click.argument("pay_id")
1052
+ @click.pass_context
1053
+ @handle_errors
1054
+ def nodes_reboot(ctx, pay_id):
1055
+ """Reboot a node."""
1056
+ client = require_client(ctx)
1057
+ _render(client.nodes_power(pay_id, "reboot"), lambda d: _print_action(d, title="Reboot Queued"))
1058
+
1059
+
1060
+ @nodes.command("status")
1061
+ @click.argument("pay_id")
1062
+ @click.pass_context
1063
+ @handle_errors
1064
+ def nodes_status(ctx, pay_id):
1065
+ """Live status (state, CPU, memory, disk, uptime)."""
1066
+ client = require_client(ctx)
1067
+ _render(client.nodes_status(pay_id), _print_node_status)
1068
+
1069
+
1070
+ @nodes.command("rebuild")
1071
+ @click.argument("pay_id")
1072
+ @click.option("-t", "--template", default=None, help="New template slug.")
1073
+ @click.option("--flavor", "flavor_id", default=None, type=int, help="New flavor ID.")
1074
+ @click.option("-y", "--yes", is_flag=True, help="Skip confirmation.")
1075
+ @click.pass_context
1076
+ @handle_errors
1077
+ def nodes_rebuild(ctx, pay_id, template, flavor_id, yes):
1078
+ """Reinstall a node's OS. Destroys all data."""
1079
+ client = require_client(ctx)
1080
+ if not yes:
1081
+ click.confirm(
1082
+ f"Rebuild {pay_id}? This will DESTROY all data on the node.", abort=True
1083
+ )
1084
+ _render(
1085
+ client.nodes_rebuild(pay_id, template=template, flavor_id=flavor_id),
1086
+ lambda d: _print_action(d, title="Rebuild Started"),
1087
+ )
1088
+
1089
+
1090
+ @nodes.command("password")
1091
+ @click.argument("pay_id")
1092
+ @click.pass_context
1093
+ @handle_errors
1094
+ def nodes_password(ctx, pay_id):
1095
+ """Generate a new root password (node must be running)."""
1096
+ client = require_client(ctx)
1097
+ result = client.nodes_password(pay_id)
1098
+ if _is_json():
1099
+ click.echo(_json.dumps(result, indent=2))
1100
+ else:
1101
+ _print_password(result.get("password", str(result)))
1102
+
1103
+
1104
+ @nodes.command("addresses")
1105
+ @click.argument("pay_id")
1106
+ @click.pass_context
1107
+ @handle_errors
1108
+ def nodes_addresses(ctx, pay_id):
1109
+ """List IP addresses for a node."""
1110
+ client = require_client(ctx)
1111
+ _render(client.nodes_addresses(pay_id), _print_addresses)
1112
+
1113
+
1114
+ @nodes.command("stats")
1115
+ @click.argument("pay_id")
1116
+ @click.option("-r", "--range", "timerange", default="hour", help="hour, day, week, month, year.")
1117
+ @click.pass_context
1118
+ @handle_errors
1119
+ def nodes_stats(ctx, pay_id, timerange):
1120
+ """Node performance stats."""
1121
+ client = require_client(ctx)
1122
+ print_raw(client.nodes_stats(pay_id, timerange))
1123
+
1124
+
1125
+ @nodes.command("activity")
1126
+ @click.argument("pay_id")
1127
+ @click.pass_context
1128
+ @handle_errors
1129
+ def nodes_activity(ctx, pay_id):
1130
+ """Recent activity log for a node."""
1131
+ client = require_client(ctx)
1132
+ print_raw(client.nodes_activity(pay_id))
1133
+
1134
+
1135
+ # ═══════════════════════════════════════════════════════════
1136
+ # webhooks
1137
+ # ═══════════════════════════════════════════════════════════
1138
+
1139
+
1140
+ @cli.group(invoke_without_command=True)
1141
+ @click.pass_context
1142
+ def webhooks(ctx):
1143
+ """Manage webhook endpoints."""
1144
+ if ctx.invoked_subcommand is None:
1145
+ ctx.invoke(webhooks_list)
1146
+
1147
+
1148
+ @webhooks.command("list")
1149
+ @click.pass_context
1150
+ @handle_errors
1151
+ def webhooks_list(ctx):
1152
+ """List all webhooks."""
1153
+ client = require_client(ctx)
1154
+ data = client.webhooks_list()
1155
+ if isinstance(data, list):
1156
+ _render(data, _print_webhooks)
1157
+ else:
1158
+ print_raw(data)
1159
+
1160
+
1161
+ @webhooks.command("create")
1162
+ @click.option("-u", "--url", required=True, help="Webhook endpoint URL.")
1163
+ @click.option(
1164
+ "-e",
1165
+ "--events",
1166
+ required=True,
1167
+ multiple=True,
1168
+ type=click.Choice(WEBHOOK_EVENTS),
1169
+ help="Event to subscribe to (repeat for multiple).",
1170
+ )
1171
+ @click.pass_context
1172
+ @handle_errors
1173
+ def webhooks_create(ctx, url, events):
1174
+ """Register a new webhook."""
1175
+ client = require_client(ctx)
1176
+ _render(client.webhooks_create(url, list(events)), _print_webhook)
1177
+
1178
+
1179
+ @webhooks.command("update")
1180
+ @click.argument("webhook_id", type=int)
1181
+ @click.option("-u", "--url", default=None, help="New URL.")
1182
+ @click.option("--enabled/--disabled", default=None, help="Enable or disable.")
1183
+ @click.option(
1184
+ "-e",
1185
+ "--events",
1186
+ multiple=True,
1187
+ type=click.Choice(WEBHOOK_EVENTS),
1188
+ help="Replace events (repeat for multiple).",
1189
+ )
1190
+ @click.pass_context
1191
+ @handle_errors
1192
+ def webhooks_update(ctx, webhook_id, url, enabled, events):
1193
+ """Update a webhook's URL, status, or events."""
1194
+ client = require_client(ctx)
1195
+ events_list = list(events) if events else None
1196
+ _render(
1197
+ client.webhooks_update(webhook_id, url=url, enabled=enabled, events=events_list),
1198
+ _print_webhook,
1199
+ )
1200
+
1201
+
1202
+ @webhooks.command("delete")
1203
+ @click.argument("webhook_id", type=int)
1204
+ @click.option("-y", "--yes", is_flag=True, help="Skip confirmation.")
1205
+ @click.pass_context
1206
+ @handle_errors
1207
+ def webhooks_delete(ctx, webhook_id, yes):
1208
+ """Delete a webhook."""
1209
+ client = require_client(ctx)
1210
+ if not yes:
1211
+ click.confirm(f"Delete webhook {webhook_id}?", abort=True)
1212
+ client.webhooks_delete(webhook_id)
1213
+ print_success(f"Webhook {webhook_id} deleted.")
1214
+
1215
+
1216
+ @webhooks.command("test")
1217
+ @click.argument("webhook_id", type=int)
1218
+ @click.pass_context
1219
+ @handle_errors
1220
+ def webhooks_test(ctx, webhook_id):
1221
+ """Send a test payload to a webhook."""
1222
+ client = require_client(ctx)
1223
+ result = client.webhooks_test(webhook_id)
1224
+ if _is_json():
1225
+ click.echo(_json.dumps(result, indent=2))
1226
+ elif result.get("sent"):
1227
+ print_success(f"Test payload sent to webhook {webhook_id}.")
1228
+ else:
1229
+ print_error("Test failed.")
1230
+ sys.exit(1)
1231
+
1232
+
1233
+ @webhooks.command("deliveries")
1234
+ @click.argument("webhook_id", type=int)
1235
+ @click.pass_context
1236
+ @handle_errors
1237
+ def webhooks_deliveries(ctx, webhook_id):
1238
+ """View delivery history for a webhook."""
1239
+ client = require_client(ctx)
1240
+ print_raw(client.webhooks_deliveries(webhook_id))
1241
+
1242
+
1243
+ # ═══════════════════════════════════════════════════════════
1244
+ # reference commands
1245
+ # ═══════════════════════════════════════════════════════════
1246
+
1247
+
1248
+ @cli.command()
1249
+ @click.pass_context
1250
+ @handle_errors
1251
+ def plans(ctx):
1252
+ """List available plans (CPU, RAM, disk tiers)."""
1253
+ client = require_client(ctx)
1254
+ data = client.plans()
1255
+ if isinstance(data, list):
1256
+ _render(data, _print_plans)
1257
+ else:
1258
+ print_raw(data)
1259
+
1260
+
1261
+ @cli.command()
1262
+ @click.pass_context
1263
+ @handle_errors
1264
+ def regions(ctx):
1265
+ """List available regions."""
1266
+ client = require_client(ctx)
1267
+ data = client.regions()
1268
+ if isinstance(data, list):
1269
+ _render(data, _print_regions)
1270
+ else:
1271
+ print_raw(data)
1272
+
1273
+
1274
+ @cli.command()
1275
+ @click.pass_context
1276
+ @handle_errors
1277
+ def templates(ctx):
1278
+ """List available OS templates and flavors."""
1279
+ client = require_client(ctx)
1280
+ data = client.templates()
1281
+ if isinstance(data, list):
1282
+ _render(data, _print_templates)
1283
+ else:
1284
+ print_raw(data)
1285
+
1286
+
1287
+ if __name__ == "__main__":
1288
+ cli()