multicloud-cli 0.12.0__tar.gz → 0.13.1__tar.gz

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.
Files changed (47) hide show
  1. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/PKG-INFO +4 -1
  2. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/README.md +3 -0
  3. multicloud_cli-0.13.1/multicloud_cli/__init__.py +1 -0
  4. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/api.py +16 -8
  5. multicloud_cli-0.13.1/multicloud_cli/db_access.py +162 -0
  6. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/main.py +2 -0
  7. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/net.py +25 -6
  8. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/pool.py +174 -0
  9. multicloud_cli-0.13.1/tests/test_db_access.py +285 -0
  10. multicloud_cli-0.13.1/tests/test_net.py +49 -0
  11. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_pool.py +162 -0
  12. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_version_check.py +1 -1
  13. multicloud_cli-0.12.0/multicloud_cli/__init__.py +0 -1
  14. multicloud_cli-0.12.0/tests/test_net.py +0 -24
  15. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/.gitignore +0 -0
  16. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/LICENSE +0 -0
  17. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/account.py +0 -0
  18. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/auth.py +0 -0
  19. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/catalog.py +0 -0
  20. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/cloud_account.py +0 -0
  21. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/config.py +0 -0
  22. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/duration.py +0 -0
  23. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/exitcodes.py +0 -0
  24. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/extend.py +0 -0
  25. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/kube.py +0 -0
  26. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/node.py +0 -0
  27. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/orgopt.py +0 -0
  28. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/output.py +0 -0
  29. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/ssh.py +0 -0
  30. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/ssh_cert.py +0 -0
  31. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/sso.py +0 -0
  32. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/multicloud_cli/version_check.py +0 -0
  33. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/pyproject.toml +0 -0
  34. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/__init__.py +0 -0
  35. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/conftest.py +0 -0
  36. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/helpers.py +0 -0
  37. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_account_extend.py +0 -0
  38. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_apply.py +0 -0
  39. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_auth.py +0 -0
  40. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_catalog.py +0 -0
  41. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_cloud_account.py +0 -0
  42. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_conventions.py +0 -0
  43. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_proxy_key.py +0 -0
  44. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_ssh.py +0 -0
  45. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_ssh_cert.py +0 -0
  46. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_sso.py +0 -0
  47. {multicloud_cli-0.12.0 → multicloud_cli-0.13.1}/tests/test_sso_session.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: multicloud-cli
3
- Version: 0.12.0
3
+ Version: 0.13.1
4
4
  Summary: mctl: the Multicloud command line: sign in, connect your cloud account, run pools
5
5
  Project-URL: Homepage, https://multicloud.io
6
6
  Author-email: Multicloud Team <info@multicloud.io>
@@ -158,6 +158,9 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
158
158
  | `mctl pool create <name>` | Make a pool. Use `--from-file pool.json` for the full request, or the flags `--github-org`, `--clouds`, `--classes`, `--max-cost-per-hour`, `--spot-policy`, `--cpu-units-requests`, `--image-by-class`, `--egress-by-class`, `--class-headroom`. A repeated run with the same `--idempotency-key` makes one pool. Put cloud keys in the file, not on the command line. |
159
159
  | `mctl pool update <pool>` | Change `--max-cost-per-hour`, `--max-servers`, `--classes`, `--spot-policy`, `--cpu-units-requests`, `--clouds` or settings: `--set NAME=VALUE` (repeat; VALUE is JSON, else text; the name lists `instance_types`, `excluded_instance_types`, `accelerator_names`, `excluded_accelerator_names`, `accelerator_vendors` and `excluded_accelerator_vendors` also take comma-separated names; `grant.cpu` for grant fields), `--reset NAME`, `--settings JSON\|@file`. Only the options you give change. `mctl pool show` prints the settings, or `default: X` where a setting is unset. On an Extend pool with a `PENDING` or `READY` peering, a change of `accelerator_names` or `excluded_accelerator_names` fails with 409 `POOL_HAS_PEERINGS`: revoke the peering first, or create a second pool. |
160
160
  | `mctl pool show <pool>` / `cluster <pool>` | The pool, or its machines and their cost. |
161
+ | `mctl pool diagnose <pool>` | Why a pool or its Extend bridge does not work: the pool's lifecycle and readiness gates, and for each bridge replica what the pool sees of its WireGuard handshake, with a hint. Reads only; it never wakes a hibernated pool. `--json` prints the raw answer. |
162
+ | `mctl pool cpu-sizing <pool>` | Recommended cpu-units request and burst limit per workload container, from the last 14 days of usage (72 qualifying hours needed), with the current request, observed P95/MAX and `clipped`. `--namespace`, `--owner-kind`, `--window-days`, `--clipped-only`, `--json`. Reads only. |
163
+ | `mctl pool cpu-sizing-history <pool> <namespace> <owner-kind> <owner-name>` | The hourly cpu-units of one workload, per container. `--window-days`, `--json`. |
161
164
  | `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
162
165
  | `mctl pool delete <pool> [-y]` | Delete a pool for good. It asks first; without a terminal, `-y` is required. To pause a pool, use `hibernate`. |
163
166
  | `mctl pool rotate-credentials <pool>` / `rotation-status <pool>` | Renew the pool's access credentials; show the progress of the last renewal. |
@@ -127,6 +127,9 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
127
127
  | `mctl pool create <name>` | Make a pool. Use `--from-file pool.json` for the full request, or the flags `--github-org`, `--clouds`, `--classes`, `--max-cost-per-hour`, `--spot-policy`, `--cpu-units-requests`, `--image-by-class`, `--egress-by-class`, `--class-headroom`. A repeated run with the same `--idempotency-key` makes one pool. Put cloud keys in the file, not on the command line. |
128
128
  | `mctl pool update <pool>` | Change `--max-cost-per-hour`, `--max-servers`, `--classes`, `--spot-policy`, `--cpu-units-requests`, `--clouds` or settings: `--set NAME=VALUE` (repeat; VALUE is JSON, else text; the name lists `instance_types`, `excluded_instance_types`, `accelerator_names`, `excluded_accelerator_names`, `accelerator_vendors` and `excluded_accelerator_vendors` also take comma-separated names; `grant.cpu` for grant fields), `--reset NAME`, `--settings JSON\|@file`. Only the options you give change. `mctl pool show` prints the settings, or `default: X` where a setting is unset. On an Extend pool with a `PENDING` or `READY` peering, a change of `accelerator_names` or `excluded_accelerator_names` fails with 409 `POOL_HAS_PEERINGS`: revoke the peering first, or create a second pool. |
129
129
  | `mctl pool show <pool>` / `cluster <pool>` | The pool, or its machines and their cost. |
130
+ | `mctl pool diagnose <pool>` | Why a pool or its Extend bridge does not work: the pool's lifecycle and readiness gates, and for each bridge replica what the pool sees of its WireGuard handshake, with a hint. Reads only; it never wakes a hibernated pool. `--json` prints the raw answer. |
131
+ | `mctl pool cpu-sizing <pool>` | Recommended cpu-units request and burst limit per workload container, from the last 14 days of usage (72 qualifying hours needed), with the current request, observed P95/MAX and `clipped`. `--namespace`, `--owner-kind`, `--window-days`, `--clipped-only`, `--json`. Reads only. |
132
+ | `mctl pool cpu-sizing-history <pool> <namespace> <owner-kind> <owner-name>` | The hourly cpu-units of one workload, per container. `--window-days`, `--json`. |
130
133
  | `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
131
134
  | `mctl pool delete <pool> [-y]` | Delete a pool for good. It asks first; without a terminal, `-y` is required. To pause a pool, use `hibernate`. |
132
135
  | `mctl pool rotate-credentials <pool>` / `rotation-status <pool>` | Renew the pool's access credentials; show the progress of the last renewal. |
@@ -0,0 +1 @@
1
+ __version__ = "0.13.1"
@@ -21,7 +21,10 @@ CONSOLE_SCOPE_NAMES = {"org:read": "Pools: Read", "org:write": "Pools: Manage",
21
21
 
22
22
  class ApiError(Exception):
23
23
  """The call failed. ``status`` is the HTTP status, or None when there was no answer.
24
- ``exit_code`` is the exit code of ``mctl`` for it (see ``exitcodes``)."""
24
+ ``exit_code`` is the exit code of ``mctl`` for it (see ``exitcodes``). ``connect_failed`` is True when no
25
+ connection could be made at all (a ``requests.ConnectionError`` other than a TLS or proxy failure)."""
26
+
27
+ connect_failed = False
25
28
 
26
29
  def __init__(self, message: str, status: Optional[int] = None, exit_code: Optional[int] = None):
27
30
  super().__init__(message)
@@ -55,14 +58,19 @@ def _detail_text(data: Any) -> Optional[str]:
55
58
 
56
59
 
57
60
  def _send(method: str, url: str, body: Optional[Dict[str, Any]], headers: Dict[str, str],
58
- params: Optional[Dict[str, Any]] = None, ipv4_only: bool = False) -> requests.Response:
61
+ params: Optional[Dict[str, Any]] = None, ipv4_only: bool = False,
62
+ ipv6_only: bool = False) -> requests.Response:
59
63
  extra = {"params": params} if params else {} # a list value becomes one repeated key
60
64
  try:
61
65
  # No redirects: requests would carry the credential header to another host.
62
66
  return net.request(method, url, json=body, timeout=TIMEOUT_S, allow_redirects=False, headers=headers,
63
- ipv4_only=ipv4_only, **extra)
67
+ ipv4_only=ipv4_only, ipv6_only=ipv6_only, **extra)
64
68
  except requests.RequestException as ex:
65
- raise ApiError(f"Could not reach the API: {ex}")
69
+ error = ApiError(f"Could not reach the API: {ex}")
70
+ # A TLS or proxy failure is a ConnectionError too, but not "no route over this family": keep it an error.
71
+ error.connect_failed = (isinstance(ex, requests.ConnectionError)
72
+ and not isinstance(ex, (requests.exceptions.SSLError, requests.exceptions.ProxyError)))
73
+ raise error
66
74
 
67
75
 
68
76
  def _sso_org(slug: Optional[str], token: str, explicit: bool = True) -> str:
@@ -88,14 +96,14 @@ def call(method: str, org: Optional[str], path: str = "", *, body: Optional[Dict
88
96
  headers: Optional[Dict[str, str]] = None, accept: Iterable[int] = (200, 201, 202),
89
97
  scope: Optional[str] = None, pass_codes: Iterable[str] = (),
90
98
  params: Optional[Dict[str, Any]] = None, org_scoped: bool = True,
91
- ipv4_only: bool = False, prefer_sso: bool = False) -> Dict[str, Any]:
99
+ ipv4_only: bool = False, ipv6_only: bool = False, prefer_sso: bool = False) -> Dict[str, Any]:
92
100
  """One API call. Returns the JSON body with ``_status`` added; raises ``ApiError`` on other statuses.
93
101
 
94
102
  ``scope`` names the API key scope this call needs; a 401 or 403 then says that it may be missing.
95
103
  A failed answer whose error code is in ``pass_codes`` is returned like a success.
96
104
  ``params`` are query parameters. ``org_scoped=False`` calls ``/api/v1{path}`` with no organization in the URL:
97
105
  an SSO call then needs no organization, and ``MULTICLOUD_API_KEY`` needs none either (a stored key still
98
- needs one to be found). ``ipv4_only`` connects over IPv4 only (the SSH grant routes). ``prefer_sso`` keeps the
106
+ needs one to be found). ``ipv4_only`` / ``ipv6_only`` connect over one address family only (the grant routes). ``prefer_sso`` keeps the
99
107
  SSO token on a platform route even when the named org has a stored key or ``MULTICLOUD_API_KEY`` is set: the
100
108
  operator routes check a realm role,
101
109
  which an API key never holds."""
@@ -134,7 +142,7 @@ def call(method: str, org: Optional[str], path: str = "", *, body: Optional[Dict
134
142
  except config.ConfigError as ex:
135
143
  raise ApiError(str(ex))
136
144
  url = f"{base}/api/v1/orgs/{quote(slug, safe='')}{path}" if org_scoped else f"{base}/api/v1{path}"
137
- r = _send(method, url, body, {**credential, **(headers or {})}, params, ipv4_only)
145
+ r = _send(method, url, body, {**credential, **(headers or {})}, params, ipv4_only, ipv6_only)
138
146
  if r.status_code == 401 and use_sso:
139
147
  # The access token was refused (the session may have ended on the server): refresh once and retry once.
140
148
  try:
@@ -142,7 +150,7 @@ def call(method: str, org: Optional[str], path: str = "", *, body: Optional[Dict
142
150
  except auth.AuthError as ex:
143
151
  raise ApiError(str(ex), 401)
144
152
  r = _send(method, url, body, {"Authorization": f"Bearer {token}", **(headers or {})}, params,
145
- ipv4_only)
153
+ ipv4_only, ipv6_only)
146
154
  try:
147
155
  data = r.json() if r.text else {}
148
156
  except ValueError:
@@ -0,0 +1,162 @@
1
+ """``mctl db-access``: open the database allow-list (tcp/5432) for your own IP. For Multicloud platform admins.
2
+
3
+ These commands call ``/api/v1/db-access`` (not scoped to an organization). They need the SSO sign-in of an operator
4
+ (realm role ``multicloud-admins``); an API key never reaches them. The group is hidden: it is not in ``mctl --help``.
5
+ The API takes the address of the caller from the connection, and ``api.multicloud.io`` has A and AAAA records, so
6
+ ``allow`` makes one call over IPv4 and one over IPv6 and opens both addresses. A host with no IPv6 route gets IPv4 only.
7
+ """
8
+ from datetime import datetime, timezone
9
+ from typing import Any, Dict, List, Optional
10
+
11
+ import click
12
+
13
+ from . import api, exitcodes
14
+ from .duration import duration_option
15
+ from .output import dump as _dump, echo as _echo, json_option, no_headers_option, plain as _plain, quiet_option, run, table as _table
16
+
17
+ MIN_TTL_S, MAX_TTL_S = 300, 86400 # the API accepts 5 minutes to 24 hours
18
+ APPLY_NOTE = "The scheduler applies it within about a minute."
19
+ IPV6_WARNING = ("Warning: the /64 covers every device on this network. On a shared network (cafe, hotel) "
20
+ "use --ipv4-only.")
21
+ NO_IPV6_NOTE = "No IPv6 route to the API: IPv4 only."
22
+ NO_IPV4_NOTE = "No IPv4 route to the API: IPv6 only."
23
+ REVOKE_NOTE = ("The scheduler removes the rule after its removal grace (10 minutes), so access ends within "
24
+ "about 11 minutes.")
25
+
26
+
27
+ class DbAccessError(exitcodes.CliError):
28
+ connect_failed = False # no connection at all (no route to the API over this address family)
29
+
30
+
31
+ def _call(method: str, path: str, **kw) -> Dict[str, Any]:
32
+ try:
33
+ return api.call(method, None, path, org_scoped=False, prefer_sso=True, **kw)
34
+ except api.ApiError as ex:
35
+ text = str(ex)
36
+ if ex.status == 403:
37
+ text += " (db-access needs the multicloud-admins role.)"
38
+ error = DbAccessError(text, ex.exit_code)
39
+ error.connect_failed = ex.connect_failed
40
+ raise error
41
+
42
+
43
+ def _run(fn):
44
+ return run(None, lambda org: fn(), (DbAccessError, api.ApiError))
45
+
46
+
47
+ def _when(iso: Any) -> Optional[datetime]:
48
+ try:
49
+ at = datetime.fromisoformat(str(iso).replace("Z", "+00:00"))
50
+ except ValueError:
51
+ return None
52
+ return at if at.tzinfo is not None else at.replace(tzinfo=timezone.utc)
53
+
54
+
55
+ def _span(seconds: float) -> str:
56
+ minutes = int(abs(seconds) // 60)
57
+ hours, minutes = divmod(minutes, 60)
58
+ return f"{hours}h{minutes:02d}m" if hours else f"{minutes}m"
59
+
60
+
61
+ def _expires_text(iso: Any) -> str:
62
+ """``2026-11-18 21:30 CET (in 11h59m)`` in local time."""
63
+ at = _when(iso)
64
+ if at is None:
65
+ return str(iso)
66
+ left = (at - datetime.now(timezone.utc)).total_seconds()
67
+ relative = f"in {_span(left)}" if left > 0 else f"{_span(left)} ago"
68
+ return f"{at.astimezone().strftime('%Y-%m-%d %H:%M %Z')} ({relative})"
69
+
70
+
71
+ @click.group(hidden=True)
72
+ def db_access():
73
+ """Open the database allow-list for your own IP (platform admins; sign in first: mctl auth login).
74
+
75
+ allow opens your IPv4 address and, when you have a route to the API over IPv6, your IPv6 /64 network.
76
+ list shows the active grants of every admin. revoke ends one."""
77
+
78
+
79
+ @db_access.command()
80
+ @click.option("--ttl", "ttl", default="12h", show_default=True, callback=duration_option,
81
+ help="How long the access lasts: 5m to 24h (30m, 12h, 90s)")
82
+ @click.option("--ipv4-only", is_flag=True, help="Open only your IPv4 address (use it on a shared network)")
83
+ @json_option
84
+ def allow(ttl, ipv4_only, as_json):
85
+ """Open DB access for your current public IPs, or extend it."""
86
+ def go():
87
+ if not MIN_TTL_S <= ttl <= MAX_TTL_S:
88
+ raise DbAccessError(f"--ttl must be between 5m and 24h, not {ttl} seconds.", exitcodes.USAGE)
89
+ body = {"ttl_seconds": ttl}
90
+ results: List[Dict[str, Any]] = []
91
+ notes: List[str] = []
92
+ try:
93
+ results.append(_call("POST", "/db-access", body=body, ipv4_only=True))
94
+ except DbAccessError as ex:
95
+ # An IPv6-only network has no IPv4 route: go on with IPv6, unless --ipv4-only.
96
+ if not ex.connect_failed or ipv4_only:
97
+ raise
98
+ notes.append(NO_IPV4_NOTE)
99
+ no_ipv4 = ex
100
+ if not ipv4_only:
101
+ try:
102
+ results.append(_call("POST", "/db-access", body=body, ipv6_only=True))
103
+ except DbAccessError as ex:
104
+ if ex.connect_failed and results:
105
+ notes.append(NO_IPV6_NOTE)
106
+ elif ex.connect_failed:
107
+ raise no_ipv4 from ex # neither family reaches the API
108
+ elif results:
109
+ first = results[0]
110
+ raise DbAccessError(f"{ex} (The IPv4 grant {first.get('id')} for {first.get('cidr')} exists; "
111
+ f"retry, or revoke it: mctl db-access revoke {first.get('id')}.)",
112
+ ex.exit_code) from ex
113
+ else:
114
+ raise
115
+ return results, notes
116
+ results, notes = _run(go)
117
+ if as_json:
118
+ return _dump({"grants": [_plain(r) for r in results]})
119
+ for r in results:
120
+ verb = "extended" if r.get("_status") == 200 else "created"
121
+ click.echo(f"{verb} grant {r.get('id')}: {r.get('cidr')} until {_expires_text(r.get('expires_at'))}")
122
+ for note in notes:
123
+ click.echo(note)
124
+ click.echo(APPLY_NOTE)
125
+ if any(":" in str(r.get("cidr")) for r in results):
126
+ click.echo(IPV6_WARNING)
127
+
128
+
129
+ @db_access.command("list")
130
+ @click.option("--all", "show_all", is_flag=True, help="Also the grants that ended in the last 7 days")
131
+ @json_option
132
+ @quiet_option
133
+ @no_headers_option
134
+ def list_(show_all, as_json, quiet, no_headers):
135
+ """List the active grants (all admins)."""
136
+ params = {"include_expired": "true"} if show_all else None
137
+ data = _run(lambda: _call("GET", "/db-access", params=params))
138
+ if as_json:
139
+ return _dump(data)
140
+ grants = data.get("grants", [])
141
+ if quiet:
142
+ return _echo("\n".join(str(g.get("id")) for g in grants))
143
+
144
+ def end(g):
145
+ at = _when(g.get("revoked_at") or g.get("expires_at"))
146
+ if at is not None and at <= datetime.now(timezone.utc):
147
+ return f"ended {_expires_text(g.get('revoked_at') or g.get('expires_at'))}"
148
+ return _expires_text(g.get("expires_at"))
149
+ _echo(_table(("ID", "CIDR", "CREATED_BY", "EXPIRES"), [
150
+ (str(g.get("id")), str(g.get("cidr")), str(g.get("created_by") or "-"), end(g)) for g in grants],
151
+ not no_headers))
152
+
153
+
154
+ @db_access.command()
155
+ @click.argument("grant_id", metavar="ID", type=int)
156
+ @json_option
157
+ def revoke(grant_id, as_json):
158
+ """Revoke a grant."""
159
+ data = _run(lambda: _call("DELETE", f"/db-access/{grant_id}"))
160
+ if as_json:
161
+ return _dump(data)
162
+ click.echo(f"Revoked grant {grant_id}. {REVOKE_NOTE}")
@@ -14,6 +14,7 @@ from .node import node
14
14
  from .orgopt import org_option
15
15
  from .pool import pool
16
16
  from .ssh import ssh
17
+ from .db_access import db_access
17
18
 
18
19
 
19
20
  def _broken_pipe() -> int:
@@ -68,6 +69,7 @@ mctl.add_command(billing)
68
69
  mctl.add_command(extend)
69
70
  mctl.add_command(peering)
70
71
  mctl.add_command(ssh)
72
+ mctl.add_command(db_access)
71
73
  mctl.add_command(node)
72
74
 
73
75
 
@@ -11,6 +11,11 @@ from requests.adapters import HTTPAdapter
11
11
  from . import __version__, exitcodes
12
12
 
13
13
  USER_AGENT = f"mctl/{__version__}"
14
+ # The connect timeout of each address. api. and auth.multicloud.io resolve to several A and AAAA records, and
15
+ # urllib3 tries them one at a time (no Happy Eyeballs): with the read timeout as the connect timeout, one address
16
+ # that drops SYNs cost 30 s per request. The connect timeout also bounds the TLS handshake (urllib3 sets the read
17
+ # timeout only after it): TCP connect plus TLS to the API takes about 0.45 s, so 5 s leaves room for a slow link.
18
+ CONNECT_TIMEOUT_S = 5
14
19
  UPGRADE = "uv tool upgrade multicloud-cli (or pipx upgrade multicloud-cli)"
15
20
 
16
21
 
@@ -39,14 +44,28 @@ class IPv4Adapter(HTTPAdapter):
39
44
  super().init_poolmanager(connections, maxsize, block, **pool_kwargs)
40
45
 
41
46
 
42
- def request(method: str, url: str, ipv4_only: bool = False, **kw: Any) -> requests.Response:
43
- """One request. ``ipv4_only`` connects over IPv4 only: the SSH grant routes read the address of the caller as
44
- the API sees it, and ``api.multicloud.io`` has AAAA records."""
47
+ class IPv6Adapter(HTTPAdapter):
48
+ """Connects over IPv6 only. Binding the local end to ``::`` makes urllib3 skip every IPv4 (A) address: its socket
49
+ cannot bind there, so the next address is tried. A host with no IPv6 route ends in a ``ConnectionError``."""
50
+
51
+ def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
52
+ pool_kwargs["source_address"] = ("::", 0)
53
+ super().init_poolmanager(connections, maxsize, block, **pool_kwargs)
54
+
55
+
56
+ def request(method: str, url: str, ipv4_only: bool = False, ipv6_only: bool = False,
57
+ **kw: Any) -> requests.Response:
58
+ """One request. ``ipv4_only`` / ``ipv6_only`` connect over one address family only: the grant routes read the
59
+ address of the caller as the API sees it, and ``api.multicloud.io`` has A and AAAA records."""
45
60
  kw["headers"] = {"User-Agent": USER_AGENT, **(kw.get("headers") or {})}
46
- if ipv4_only:
61
+ timeout = kw.get("timeout")
62
+ if isinstance(timeout, (int, float)) and not isinstance(timeout, bool) and timeout > 0: # a pair is kept as given
63
+ kw["timeout"] = (min(CONNECT_TIMEOUT_S, timeout), timeout)
64
+ if ipv4_only or ipv6_only:
65
+ adapter = IPv6Adapter if ipv6_only else IPv4Adapter
47
66
  with requests.Session() as session:
48
- session.mount("https://", IPv4Adapter())
49
- session.mount("http://", IPv4Adapter())
67
+ session.mount("https://", adapter())
68
+ session.mount("http://", adapter())
50
69
  r = session.request(method, url, **kw)
51
70
  else:
52
71
  r = requests.request(method, url, **kw)
@@ -199,6 +199,180 @@ def show(ctx, pool_ref, as_json):
199
199
  click.echo(json.dumps(_plain(data), indent=2, sort_keys=True) if as_json else _readable(data))
200
200
 
201
201
 
202
+ #: Help text of each bridge hint code of GET /pools/{id}/diagnostics. The API sends the code only.
203
+ DIAGNOSE_HINTS = {
204
+ "NO_HANDSHAKE_AT_POOL": "The pool never received a WireGuard handshake from this replica. "
205
+ "Check that outbound UDP 51820 is allowed from the consumer cluster.",
206
+ "STALE_HANDSHAKE_AT_POOL": "The pool saw a handshake from this replica before, but has no recent handshake. "
207
+ "Check that the replica runs and that outbound UDP 51820 is still allowed.",
208
+ "POOL_NODE_AGENT_OUTDATED": "The pool's nodes run an older node agent that does not report WireGuard peers. "
209
+ "The handshake state is unknown until the nodes are replaced.",
210
+ "REPLICA_NOT_A_PEER_YET": "The pool's nodes do not list this replica as a WireGuard peer yet. "
211
+ "Wait a few minutes. If it stays, check the pool's proxy publishing above.",
212
+ "POOL_NOT_RUNNING": "The pool is not running (new, hibernated, hibernating or waking), so its nodes report no "
213
+ "handshake state. Run the check again when the pool is RUNNING.",
214
+ }
215
+
216
+
217
+ def _diagnose_text(d: Dict[str, Any]) -> str:
218
+ """The readable form of a PoolDiagnosticsView: the pool lines, then one block per bridge replica."""
219
+ pid = d.get("pool_id")
220
+ if d.get("lifecycle") is None:
221
+ out = [f"Pool {pid}: no state recorded yet"]
222
+ else:
223
+ head = f"Pool {pid}: {d['lifecycle']}"
224
+ if d.get("lifecycle_since"):
225
+ head += f" since {d['lifecycle_since']}"
226
+ out = [head]
227
+ if d.get("observed_at"):
228
+ out.append(f"Checked: {d['observed_at']}")
229
+ gates = d.get("gates")
230
+ if gates:
231
+ out.append("Gates: " + ", ".join(f"{k} {'yes' if gates.get(k) else 'no'}"
232
+ for k in ("tcp_ready", "liqo_synced", "rbac_ready")))
233
+ if d.get("gate_code"):
234
+ out.append(f"Waiting for: {d['gate_code']}")
235
+ if d.get("wg_proxy_publish_blocked"):
236
+ out.append(f"Proxy list not published: {d['wg_proxy_publish_blocked']}")
237
+ if d.get("provisioning_breaker"):
238
+ out.append(f"Provisioning breaker: {d['provisioning_breaker']}")
239
+ bridges = d.get("bridges") or []
240
+ if not bridges:
241
+ out.append("Bridges: none")
242
+ for b in bridges:
243
+ out.append("")
244
+ out.append(f"Bridge {b.get('replica')} (peering {b.get('peering_id')}): {b.get('status')}")
245
+ handshake = str(b.get("pool_handshake", "unknown"))
246
+ if b.get("pool_handshake_at"):
247
+ handshake += f" (last {b['pool_handshake_at']})"
248
+ out.append(f" Pool handshake: {handshake}")
249
+ fresh, total = b.get("pool_nodes_fresh"), b.get("pool_nodes_total")
250
+ out.append(" Pool nodes with a fresh handshake: "
251
+ + ("-" if total is None else f"{0 if fresh is None else fresh} of {total}"))
252
+ out.append(f" Source IP: {b.get('source_ip') or '-'}")
253
+ out.append(f" Last seen: {b.get('last_seen_at') or '-'}")
254
+ if b.get("hint"):
255
+ out.append(f" {b['hint']}: {DIAGNOSE_HINTS[b['hint']]}" if b["hint"] in DIAGNOSE_HINTS
256
+ else f" {b['hint']}")
257
+ return "\n".join(out)
258
+
259
+
260
+ @pool.command()
261
+ @click.argument("pool_ref", metavar="POOL")
262
+ @json_option
263
+ @click.pass_context
264
+ def diagnose(ctx, pool_ref, as_json):
265
+ """Explain why a pool or its Extend bridge does not work (id or name).
266
+
267
+ Shows the pool's lifecycle and readiness gates and, for each bridge replica, what the pool sees of its
268
+ WireGuard handshake. Reads only: it never wakes a hibernated pool."""
269
+ def go(org):
270
+ return _call(org, "GET", f"/pools/{resolve(org, pool_ref)}/diagnostics", READ)
271
+ data = _run(ctx, go)
272
+ click.echo(json.dumps(_plain(data), indent=2, sort_keys=True) if as_json else _diagnose_text(data))
273
+
274
+
275
+ #: GET /pools/{id}/cpu-sizing keeps 35 days of usage; the recommendation always uses 14.
276
+ CPU_SIZING_WINDOW = click.IntRange(1, 35)
277
+
278
+
279
+ def _units(value) -> str:
280
+ return "-" if value is None else str(value)
281
+
282
+
283
+ def _cpu_now(w: Dict[str, Any]) -> str:
284
+ """The current request/limit: cpu-units when the pod spec sets them, else raw millicores."""
285
+ cur = w.get("current") or {}
286
+ if w.get("setting_status") == "manifest_units":
287
+ return f"{_units(cur.get('request_units'))}/{_units(cur.get('limit_units'))}u"
288
+ if w.get("setting_status") == "manifest_raw":
289
+ return f"{_units(cur.get('request_mcpu'))}/{_units(cur.get('limit_mcpu'))}m"
290
+ return "-"
291
+
292
+
293
+ def _cpu_recommended(rec: Dict[str, Any]) -> str:
294
+ if rec.get("status") == "ok":
295
+ return f"{rec.get('request_units')}/{rec.get('limit_units')}u"
296
+ return f"wait ({rec.get('qualifying_hours')}/{rec.get('required_hours')}h)"
297
+
298
+
299
+ def format_cpu_sizing(data: Dict[str, Any], headers: bool = True) -> str:
300
+ rows = []
301
+ for w in data.get("workloads", []):
302
+ obs, rec = w.get("observed") or {}, w.get("recommendation") or {}
303
+ rows.append((f"{w.get('namespace')}/{w.get('owner_kind')}/{w.get('owner_name')}", str(w.get("container")),
304
+ _cpu_now(w), _units(obs.get("p95_units")), _units(obs.get("max_units")),
305
+ _cpu_recommended(rec), "yes" if w.get("clipped") else "no"))
306
+ return _table(("WORKLOAD", "CONTAINER", "NOW (REQ/LIM)", "P95", "MAX", "RECOMMENDED (REQ/LIM)", "CLIPPED"),
307
+ rows, headers)
308
+
309
+
310
+ @pool.command(name="cpu-sizing")
311
+ @click.argument("pool_ref", metavar="POOL")
312
+ @click.option("--namespace", default=None, help="Only this namespace")
313
+ @click.option("--owner-kind", default=None, help="Only this owner kind, e.g. Deployment")
314
+ @click.option("--window-days", type=CPU_SIZING_WINDOW, default=None,
315
+ help="Days for the observed P95 and MAX (1-35, default 14). Never changes the recommendation")
316
+ @click.option("--clipped-only", is_flag=True, default=False, help="Only workloads whose CPU limit clipped the peak")
317
+ @json_option
318
+ @no_headers_option
319
+ @click.pass_context
320
+ def cpu_sizing(ctx, pool_ref, namespace, owner_kind, window_days, clipped_only, as_json, no_headers):
321
+ """Show cpu-units recommendations per workload of a pool (id or name).
322
+
323
+ NOW is the current request/limit from the pod spec (u = cpu-units, m = raw millicores); P95 (the 95th
324
+ percentile of the hourly P95 values) and MAX are the observed cpu-units; RECOMMENDED is the request/limit from the last 14 days, or "wait" with the
325
+ qualifying hours so far (72 are needed). Reads only: nothing is applied."""
326
+ params = {k: v for k, v in (("namespace", namespace), ("owner_kind", owner_kind),
327
+ ("window_days", window_days)) if v is not None}
328
+ if clipped_only:
329
+ params["clipped_only"] = "true"
330
+
331
+ def go(org):
332
+ return _call(org, "GET", f"/pools/{resolve(org, pool_ref)}/cpu-sizing", READ, params=params or None)
333
+ data = _run(ctx, go)
334
+ if as_json:
335
+ return _dump(data)
336
+ _echo(format_cpu_sizing(data, not no_headers))
337
+
338
+
339
+ def _history_text(d: Dict[str, Any]) -> str:
340
+ out = [f"{d.get('namespace')}/{d.get('owner_kind')}/{d.get('owner_name')} in pool {d.get('pool_id')}, "
341
+ f"last {d.get('window_days')} days"]
342
+ for c in d.get("containers", []):
343
+ rec = c.get("recommendation") or {}
344
+ out += ["", f"Container {c.get('container')}: recommended {_cpu_recommended(rec)}"
345
+ + (", CLIPPED: the CPU limit cut the peak" if c.get("clipped") else "")]
346
+ out.append(_table(("HOUR", "SAMPLES", "AVG", "P95", "MAX", "REQ", "LIM"), [
347
+ (str(p.get("hour")), str(p.get("samples")), _units(p.get("avg_units")), _units(p.get("p95_units")),
348
+ _units(p.get("max_units")), _units(p.get("request_units")), _units(p.get("limit_units")))
349
+ for p in c.get("points", [])], True))
350
+ return "\n".join(out)
351
+
352
+
353
+ @pool.command(name="cpu-sizing-history")
354
+ @click.argument("pool_ref", metavar="POOL")
355
+ @click.argument("namespace")
356
+ @click.argument("owner_kind", metavar="OWNER_KIND")
357
+ @click.argument("owner_name", metavar="OWNER_NAME")
358
+ @click.option("--window-days", type=CPU_SIZING_WINDOW, default=None, help="Days of hourly points (1-35, default 14)")
359
+ @json_option
360
+ @click.pass_context
361
+ def cpu_sizing_history(ctx, pool_ref, namespace, owner_kind, owner_name, window_days, as_json):
362
+ """Show the hourly cpu-units usage of one workload, per container (values in cpu-units)."""
363
+ from urllib.parse import quote
364
+ segments = "/".join(quote(s, safe="") for s in (namespace, owner_kind, owner_name))
365
+ params = {"window_days": window_days} if window_days is not None else None
366
+
367
+ def go(org):
368
+ return _call(org, "GET", f"/pools/{resolve(org, pool_ref)}/cpu-sizing/workloads/{segments}/history", READ,
369
+ params=params)
370
+ data = _run(ctx, go)
371
+ if as_json:
372
+ return _dump(data)
373
+ _echo(_history_text(data))
374
+
375
+
202
376
  def _json_value(ctx, param, value):
203
377
  """A JSON value, or ``@path`` to read it from a file (``@-``: standard input)."""
204
378
  if value is None:
@@ -0,0 +1,285 @@
1
+ """mctl db-access: operator access to the database allow-list. The API is faked at the ``api.call`` seam."""
2
+ import json
3
+ from datetime import datetime, timedelta, timezone
4
+
5
+ import pytest
6
+ import requests
7
+ from click.testing import CliRunner
8
+
9
+ from multicloud_cli import api, net
10
+ from multicloud_cli.main import mctl
11
+
12
+ V4 = "46.116.212.65/32"
13
+ V6 = "2a01:4f8:1c1c:1234::/64"
14
+
15
+
16
+ def runner():
17
+ try:
18
+ return CliRunner(mix_stderr=False)
19
+ except TypeError:
20
+ return CliRunner()
21
+
22
+
23
+ def invoke(*args, **kw):
24
+ return runner().invoke(mctl, list(args), **kw)
25
+
26
+
27
+ def iso(seconds_from_now):
28
+ return (datetime.now(timezone.utc) + timedelta(seconds=seconds_from_now)).isoformat()
29
+
30
+
31
+ def grant(gid=7, cidr=V4, left_s=43200, created_by="user:ada", revoked=None):
32
+ return {"id": gid, "cidr": cidr, "family": 6 if ":" in cidr else 4, "created_by": created_by,
33
+ "created_at": iso(-60), "expires_at": iso(left_s), "revoked_at": revoked}
34
+
35
+
36
+ class FakeApi:
37
+ def __init__(self):
38
+ self.calls = []
39
+ self.grants = []
40
+ self.v6_error = None
41
+ self.v4_error = None
42
+ self.status = 201
43
+
44
+ def posts(self):
45
+ return [c for c in self.calls if c[0] == "POST"]
46
+
47
+ def __call__(self, method, org, path, **kw):
48
+ self.calls.append((method, path, kw))
49
+ if method == "POST" and path == "/db-access":
50
+ if kw.get("ipv6_only"):
51
+ if self.v6_error:
52
+ raise self.v6_error
53
+ return {**grant(gid=2, cidr=V6, left_s=kw["body"]["ttl_seconds"]), "_status": self.status}
54
+ if self.v4_error:
55
+ raise self.v4_error
56
+ return {**grant(gid=1, cidr=V4, left_s=kw["body"]["ttl_seconds"]), "_status": self.status}
57
+ if method == "GET" and path == "/db-access":
58
+ return {"grants": self.grants, "_status": 200}
59
+ if method == "DELETE" and path.startswith("/db-access/"):
60
+ return {**grant(gid=int(path.rsplit("/", 1)[1])), "revoked_at": iso(0), "_status": 200}
61
+ raise AssertionError(f"unexpected call {method} {path}")
62
+
63
+
64
+ @pytest.fixture
65
+ def fake(monkeypatch):
66
+ f = FakeApi()
67
+ monkeypatch.setattr(api, "call", f)
68
+ return f
69
+
70
+
71
+ # --- allow -------------------------------------------------------------------------------------------------------
72
+
73
+ def test_allow_calls_both_families_and_prints_each_grant(fake):
74
+ r = invoke("db-access", "allow")
75
+ assert r.exit_code == 0, r.stderr
76
+ [(m1, p1, kw1), (m2, p2, kw2)] = fake.posts()
77
+ assert (m1, p1, kw1["body"]) == ("POST", "/db-access", {"ttl_seconds": 43200})
78
+ assert kw1["ipv4_only"] is True and not kw1.get("ipv6_only")
79
+ assert kw2["ipv6_only"] is True and not kw2.get("ipv4_only") and kw2["body"] == {"ttl_seconds": 43200}
80
+ assert all(c[2]["prefer_sso"] is True and c[2]["org_scoped"] is False for c in fake.posts())
81
+ assert V4 in r.stdout and V6 in r.stdout
82
+ assert r.stdout.count("created") == 2 and "in 11h59m" in r.stdout or "in 12h" in r.stdout
83
+ assert "The scheduler applies it within about a minute." in r.stdout
84
+
85
+
86
+ def test_allow_warns_about_the_ipv6_prefix(fake):
87
+ r = invoke("db-access", "allow")
88
+ assert "/64 covers every device on this network" in r.stdout
89
+ assert "--ipv4-only" in r.stdout
90
+
91
+
92
+ def test_allow_says_extended_on_200(fake):
93
+ fake.status = 200
94
+ r = invoke("db-access", "allow")
95
+ assert r.stdout.count("extended") == 2 and "created" not in r.stdout
96
+
97
+
98
+ def test_ipv4_only_skips_ipv6(fake):
99
+ r = invoke("db-access", "allow", "--ipv4-only")
100
+ assert r.exit_code == 0, r.stderr
101
+ assert len(fake.posts()) == 1 and fake.posts()[0][2]["ipv4_only"] is True
102
+ assert V4 in r.stdout and V6 not in r.stdout and "/64" not in r.stdout
103
+
104
+
105
+ def test_ipv6_connect_error_succeeds_with_a_note(fake):
106
+ err = api.ApiError("Could not reach the API: no route")
107
+ err.connect_failed = True
108
+ fake.v6_error = err
109
+ r = invoke("db-access", "allow")
110
+ assert r.exit_code == 0, r.stderr
111
+ assert V4 in r.stdout and V6 not in r.stdout and "/64 covers" not in r.stdout
112
+ assert "No IPv6 route" in r.stdout and "IPv4 only" in r.stdout
113
+ assert "The scheduler applies it" in r.stdout
114
+
115
+
116
+ def no_route():
117
+ err = api.ApiError("Could not reach the API: no route")
118
+ err.connect_failed = True
119
+ return err
120
+
121
+
122
+ def test_ipv6_only_network_grants_ipv6_with_a_note(fake):
123
+ fake.v4_error = no_route()
124
+ r = invoke("db-access", "allow")
125
+ assert r.exit_code == 0, r.stderr
126
+ assert V6 in r.stdout and "No IPv4 route" in r.stdout and "/64 covers" in r.stdout
127
+
128
+
129
+ def test_no_route_at_all_fails(fake):
130
+ fake.v4_error, fake.v6_error = no_route(), no_route()
131
+ r = invoke("db-access", "allow")
132
+ assert r.exit_code != 0 and "Could not reach the API" in r.stderr
133
+
134
+
135
+ def test_ipv4_only_with_no_ipv4_route_fails(fake):
136
+ fake.v4_error = no_route()
137
+ r = invoke("db-access", "allow", "--ipv4-only")
138
+ assert r.exit_code != 0 and len(fake.posts()) == 1
139
+
140
+
141
+ def test_tls_error_is_not_a_missing_route(monkeypatch):
142
+ import requests
143
+ from multicloud_cli import net
144
+
145
+ def boom(*a, **kw):
146
+ raise requests.exceptions.SSLError("certificate verify failed")
147
+ monkeypatch.setattr(net, "request", boom)
148
+ with pytest.raises(api.ApiError) as ei:
149
+ api.call("GET", None, "/db-access", org_scoped=False, ipv6_only=True)
150
+ assert ei.value.connect_failed is False
151
+
152
+
153
+ def test_ipv6_http_error_still_fails(fake):
154
+ fake.v6_error = api.ApiError("The client address is not a public IPv6 address", 400)
155
+ r = invoke("db-access", "allow")
156
+ assert r.exit_code != 0 and "not a public IPv6 address" in r.stderr
157
+ assert "IPv4 grant" in r.stderr and "mctl db-access revoke" in r.stderr
158
+
159
+
160
+ def test_ipv4_failure_fails_and_skips_ipv6(monkeypatch):
161
+ calls = []
162
+
163
+ def boom(method, org, path, **kw):
164
+ calls.append(kw)
165
+ raise api.ApiError("The client address 10.0.0.1 is not a public IPv4 address", 400)
166
+ monkeypatch.setattr(api, "call", boom)
167
+ r = invoke("db-access", "allow")
168
+ assert r.exit_code != 0 and len(calls) == 1
169
+
170
+
171
+ def test_forbidden_names_the_role(monkeypatch):
172
+ def forbidden(method, org, path, **kw):
173
+ raise api.ApiError("Forbidden", 403)
174
+ monkeypatch.setattr(api, "call", forbidden)
175
+ for args in (("allow",), ("list",), ("revoke", "7")):
176
+ r = invoke("db-access", *args)
177
+ assert r.exit_code == 3, args
178
+ assert "(db-access needs the multicloud-admins role.)" in r.stderr
179
+
180
+
181
+ @pytest.mark.parametrize("value,seconds", [("2h", 7200), ("30m", 1800), ("300", 300), ("24h", 86400)])
182
+ def test_ttl_parsing(fake, value, seconds):
183
+ r = invoke("db-access", "allow", "--ttl", value)
184
+ assert r.exit_code == 0, r.stderr
185
+ assert {c[2]["body"]["ttl_seconds"] for c in fake.posts()} == {seconds}
186
+
187
+
188
+ @pytest.mark.parametrize("value", ["abc", "1m", "25h", "0"])
189
+ def test_bad_ttl_is_a_usage_error(fake, value):
190
+ r = invoke("db-access", "allow", "--ttl", value)
191
+ assert r.exit_code == 2 and not fake.calls
192
+
193
+
194
+ def test_allow_json(fake):
195
+ r = invoke("db-access", "allow", "--json")
196
+ assert r.exit_code == 0, r.stderr
197
+ assert [g["cidr"] for g in json.loads(r.stdout)["grants"]] == [V4, V6]
198
+
199
+
200
+ # --- list, revoke ------------------------------------------------------------------------------------------------
201
+
202
+ def test_list_table(fake):
203
+ fake.grants = [grant(gid=7), grant(gid=8, cidr=V6, created_by="user:bob")]
204
+ r = invoke("db-access", "list")
205
+ assert r.exit_code == 0, r.stderr
206
+ lines = r.stdout.splitlines()
207
+ assert lines[0].split()[:3] == ["ID", "CIDR", "CREATED_BY"]
208
+ assert lines[1].split()[:3] == ["7", V4, "user:ada"] and lines[2].split()[:3] == ["8", V6, "user:bob"]
209
+ assert fake.calls[0][2].get("params") is None
210
+
211
+
212
+ def test_list_all_asks_for_expired(fake):
213
+ fake.grants = [grant(gid=7, left_s=-3600, revoked=None)]
214
+ r = invoke("db-access", "list", "--all")
215
+ assert r.exit_code == 0, r.stderr
216
+ assert fake.calls[0][2]["params"] == {"include_expired": "true"}
217
+ assert "ended" in r.stdout
218
+
219
+
220
+ def test_revoke(fake):
221
+ r = invoke("db-access", "revoke", "7")
222
+ assert r.exit_code == 0, r.stderr
223
+ assert fake.calls[0][:2] == ("DELETE", "/db-access/7")
224
+ assert "Revoked grant 7" in r.stdout and "removal grace" in r.stdout
225
+
226
+
227
+ # --- transport ---------------------------------------------------------------------------------------------------
228
+
229
+ def test_ipv6_adapter_binds_the_wildcard_v6_address():
230
+ adapter = net.IPv6Adapter()
231
+ assert adapter.poolmanager.connection_pool_kw["source_address"] == ("::", 0)
232
+
233
+
234
+ def test_net_request_ipv6_only_uses_the_adapter(monkeypatch):
235
+ seen = {}
236
+
237
+ def session_request(self, method, url, **kw):
238
+ seen["adapter"] = self.get_adapter(url)
239
+ seen["kw"] = kw
240
+ return "r"
241
+ monkeypatch.setattr(requests.Session, "request", session_request)
242
+ monkeypatch.setattr(requests, "request", lambda *a, **kw: pytest.fail("plain path used"))
243
+ assert net.request("GET", "https://api.multicloud.io/x", ipv6_only=True, timeout=1) == "r"
244
+ assert isinstance(seen["adapter"], net.IPv6Adapter) and "ipv6_only" not in seen["kw"]
245
+
246
+
247
+ def test_api_call_passes_ipv6_only_to_the_transport(monkeypatch):
248
+ from .helpers import reply
249
+ monkeypatch.setenv("MULTICLOUD_API_KEY", "fake-key-0000")
250
+ seen = []
251
+ monkeypatch.setattr(net, "request", lambda m, u, **kw: seen.append(kw) or reply(200, {}))
252
+ api.call("GET", None, "/db-access", org_scoped=False, ipv6_only=True)
253
+ api.call("GET", None, "/db-access", org_scoped=False)
254
+ assert [kw["ipv6_only"] for kw in seen] == [True, False]
255
+
256
+
257
+ def test_connection_error_is_marked_connect_failed(monkeypatch):
258
+ monkeypatch.setenv("MULTICLOUD_API_KEY", "fake-key-0000")
259
+
260
+ def refuse(m, u, **kw):
261
+ raise requests.ConnectionError("Network is unreachable")
262
+ monkeypatch.setattr(net, "request", refuse)
263
+ with pytest.raises(api.ApiError) as ex:
264
+ api.call("GET", None, "/db-access", org_scoped=False, ipv6_only=True)
265
+ assert ex.value.connect_failed is True
266
+
267
+ def timeout(m, u, **kw):
268
+ raise requests.ReadTimeout("slow")
269
+ monkeypatch.setattr(net, "request", timeout)
270
+ with pytest.raises(api.ApiError) as ex:
271
+ api.call("GET", None, "/db-access", org_scoped=False)
272
+ assert ex.value.connect_failed is False
273
+
274
+
275
+ # --- hidden ------------------------------------------------------------------------------------------------------
276
+
277
+ def test_root_help_does_not_mention_db_access():
278
+ r = invoke("--help")
279
+ assert r.exit_code == 0
280
+ assert "db-access" not in r.stdout and "db_access" not in r.stdout
281
+
282
+
283
+ def test_group_help_still_works():
284
+ r = invoke("db-access", "--help")
285
+ assert r.exit_code == 0 and "allow" in r.stdout and "revoke" in r.stdout
@@ -0,0 +1,49 @@
1
+ """Every request carries User-Agent: mctl/<version>, and the package has one version."""
2
+ import requests
3
+
4
+ from multicloud_cli import __version__, net
5
+
6
+
7
+ def test_user_agent_is_added_and_headers_are_kept(monkeypatch):
8
+ seen = {}
9
+ monkeypatch.setattr(requests, "request", lambda m, u, **kw: seen.update(kw) or "r")
10
+ assert net.request("GET", "https://x", headers={"X-API-Key": "k"}, timeout=1) == "r"
11
+ assert seen["headers"] == {"User-Agent": f"mctl/{__version__}", "X-API-Key": "k"}
12
+ net.request("POST", "https://x", data={"a": "b"})
13
+ assert seen["headers"] == {"User-Agent": f"mctl/{__version__}"}
14
+
15
+
16
+ def test_no_module_calls_requests_directly():
17
+ # A direct requests call would skip the User-Agent header; only net.py may make one.
18
+ import pathlib
19
+ import re
20
+ pkg = pathlib.Path(net.__file__).parent
21
+ hits = [f"{p.name}:{i}" for p in sorted(pkg.glob("*.py")) if p.name != "net.py"
22
+ for i, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1)
23
+ if re.search(r"\brequests\.(request|get|post|put|patch|delete|head|Session)\(", line)]
24
+ assert hits == []
25
+
26
+
27
+ def test_connect_timeout_is_short_per_address(monkeypatch):
28
+ # api. and auth.multicloud.io have 6 addresses and urllib3 tries them one by one: the connect timeout applies
29
+ # per address, so one address that drops SYNs must cost CONNECT_TIMEOUT_S, not the whole read timeout.
30
+ seen = {}
31
+ monkeypatch.setattr(requests, "request", lambda m, u, **kw: seen.update(kw) or "r")
32
+ net.request("GET", "https://x", timeout=30)
33
+ assert seen["timeout"] == (net.CONNECT_TIMEOUT_S, 30)
34
+ net.request("GET", "https://x", timeout=1) # a smaller total stays the bound for both
35
+ assert seen["timeout"] == (1, 1)
36
+ net.request("GET", "https://x", timeout=0) # not a number of seconds: requests decides, as before
37
+ assert seen["timeout"] == 0
38
+ net.request("GET", "https://x", timeout=(5, 7)) # an explicit pair is kept
39
+ assert seen["timeout"] == (5, 7)
40
+ seen.clear()
41
+ net.request("GET", "https://x") # no timeout given: none is added
42
+ assert "timeout" not in seen
43
+
44
+
45
+ def test_connect_timeout_on_the_family_routes(monkeypatch):
46
+ seen = {}
47
+ monkeypatch.setattr(requests.Session, "request", lambda self, m, u, **kw: seen.update(kw) or "r")
48
+ net.request("POST", "https://x", timeout=30, ipv6_only=True)
49
+ assert seen["timeout"] == (net.CONNECT_TIMEOUT_S, 30)
@@ -489,3 +489,165 @@ def test_max_servers_outside_1_to_100_is_a_usage_error(monkeypatch):
489
489
  r, calls, _ = run(["update", "7", "--max-servers", bad], [reply(200, pool_view())], monkeypatch)
490
490
  assert r.exit_code == 2 and not calls
491
491
  assert "--max-servers" in r.stderr
492
+
493
+
494
+ # --- mctl pool diagnose (GET /pools/{id}/diagnostics) ---
495
+
496
+ def diagnostics(**extra):
497
+ """A PoolDiagnosticsView, as the Multicloud API returns it (the Triple C case: no handshake, 0 of 2 nodes)."""
498
+ body = {"schema_version": 1, "pool_id": 412, "lifecycle": "RUNNING", "lifecycle_since": "2026-11-18T09:00:00Z",
499
+ "observed_at": "2026-11-18T10:02:11Z",
500
+ "gates": {"tcp_ready": True, "liqo_synced": True, "rbac_ready": True}, "gate_code": None,
501
+ "wg_proxy_publish_blocked": None, "provisioning_breaker": None,
502
+ "bridges": [{"peering_id": 77, "replica": "extend-proxy-6c9f-abcde", "status": "ACTIVE",
503
+ "created_at": "2026-11-18T08:00:00Z", "last_seen_at": "2026-11-18T10:02:00Z",
504
+ "pool_handshake": "never", "pool_handshake_at": None, "pool_nodes_fresh": 0,
505
+ "pool_nodes_total": 2, "source_ip": None, "hint": "NO_HANDSHAKE_AT_POOL"}]}
506
+ body.update(extra)
507
+ return body
508
+
509
+
510
+ def test_diagnose_by_id_prints_the_pool_and_each_bridge(monkeypatch):
511
+ r, calls, _ = run(["diagnose", "412"], [reply(200, diagnostics())], monkeypatch)
512
+ assert r.exit_code == 0, r.output
513
+ assert len(calls) == 1 and calls[0][:2] == ("GET", f"{BASE}/pools/412/diagnostics")
514
+ assert "Pool 412: RUNNING" in r.stdout
515
+ assert "extend-proxy-6c9f-abcde" in r.stdout and "ACTIVE" in r.stdout
516
+ assert "Pool handshake: never" in r.stdout
517
+ assert "Pool nodes with a fresh handshake: 0 of 2" in r.stdout
518
+ assert "Source IP: -" in r.stdout
519
+ assert "NO_HANDSHAKE_AT_POOL" in r.stdout
520
+ assert "Check that outbound UDP 51820 is allowed from the consumer cluster." in r.stdout
521
+
522
+
523
+ def test_diagnose_by_name_resolves_with_one_list_call(monkeypatch):
524
+ listing = {"pools": [pool_view(7, "ci"), pool_view(412, "burst")]}
525
+ r, calls, _ = run(["diagnose", "burst"], [reply(200, listing), reply(200, diagnostics())], monkeypatch)
526
+ assert r.exit_code == 0, r.output
527
+ assert [c[1] for c in calls] == [f"{BASE}/pools", f"{BASE}/pools/412/diagnostics"]
528
+
529
+
530
+ def test_diagnose_json_is_the_raw_body(monkeypatch):
531
+ r, _, _ = run(["diagnose", "412", "--json"], [reply(200, diagnostics())], monkeypatch)
532
+ assert r.exit_code == 0, r.output
533
+ assert json.loads(r.stdout) == diagnostics()
534
+
535
+
536
+ @pytest.mark.parametrize("hint,text", [
537
+ ("POOL_NODE_AGENT_OUTDATED", "older node agent"),
538
+ ("STALE_HANDSHAKE_AT_POOL", "no recent handshake"),
539
+ ("REPLICA_NOT_A_PEER_YET", "as a WireGuard peer"),
540
+ ])
541
+ def test_diagnose_help_text_for_each_hint(monkeypatch, hint, text):
542
+ body = diagnostics()
543
+ body["bridges"][0].update(hint=hint, pool_handshake="unknown" if hint != "STALE_HANDSHAKE_AT_POOL" else "stale")
544
+ r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
545
+ assert hint in r.stdout and text in r.stdout
546
+
547
+
548
+ def test_diagnose_healthy_bridge_has_no_hint_and_shows_the_source_ip(monkeypatch):
549
+ body = diagnostics()
550
+ body["bridges"][0].update(pool_handshake="fresh", pool_handshake_at="2026-11-18T10:00:00Z", pool_nodes_fresh=2,
551
+ source_ip="8.8.4.4", hint=None)
552
+ r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
553
+ assert "Pool handshake: fresh" in r.stdout and "Source IP: 8.8.4.4" in r.stdout
554
+ assert "Pool nodes with a fresh handshake: 2 of 2" in r.stdout
555
+ assert "Hint" not in r.stdout and "help" not in r.stdout.lower()
556
+
557
+
558
+ def test_diagnose_unknown_hint_prints_the_code_only(monkeypatch):
559
+ body = diagnostics()
560
+ body["bridges"][0]["hint"] = "SOME_FUTURE_CODE"
561
+ r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
562
+ assert r.exit_code == 0 and "SOME_FUTURE_CODE" in r.stdout
563
+
564
+
565
+ def test_diagnose_pool_lines_for_gate_breaker_and_publish_block(monkeypatch):
566
+ body = diagnostics(lifecycle="WAKING", gate_code="TCP_NOT_READY", provisioning_breaker="capacity-starved",
567
+ wg_proxy_publish_blocked="policy-write-failed", bridges=[],
568
+ gates={"tcp_ready": False, "liqo_synced": False, "rbac_ready": False})
569
+ r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
570
+ assert "Pool 412: WAKING" in r.stdout
571
+ assert "Waiting for: TCP_NOT_READY" in r.stdout
572
+ assert "Provisioning breaker: capacity-starved" in r.stdout
573
+ assert "Proxy list not published: policy-write-failed" in r.stdout
574
+ assert "Bridges: none" in r.stdout
575
+
576
+
577
+ def test_diagnose_pool_without_a_state_row(monkeypatch):
578
+ body = diagnostics(lifecycle=None, lifecycle_since=None, observed_at=None, gates=None, bridges=[])
579
+ r, _, _ = run(["diagnose", "412"], [reply(200, body)], monkeypatch)
580
+ assert r.exit_code == 0 and "Pool 412: no state recorded yet" in r.stdout
581
+
582
+
583
+ def test_diagnose_404_exits_not_found(monkeypatch):
584
+ r, _, _ = run(["diagnose", "412"], [reply(404, {"detail": {"error": {"message": "No such pool"}}})], monkeypatch)
585
+ assert r.exit_code == 4
586
+
587
+
588
+ # --- mctl pool cpu-sizing / cpu-sizing-history (GET /pools/{id}/cpu-sizing[...]) ---
589
+
590
+ def cpu_sizing_body():
591
+ """A CpuSizingResponse: one workload with a recommendation, one still collecting data."""
592
+ rec_ok = {"status": "ok", "window_days": 14, "qualifying_hours": 120, "required_hours": 72,
593
+ "request_units": 230, "limit_units": 600}
594
+ rec_wait = {"status": "insufficient_data", "window_days": 14, "qualifying_hours": 9, "required_hours": 72,
595
+ "request_units": None, "limit_units": None}
596
+ obs = {"window_days": 14, "hours": 120, "avg_units": 150, "p95_units": 200, "max_units": 500}
597
+ return {"pool_id": 412, "window_days": 14, "generated_at": "2026-11-21T10:00:00Z", "workloads": [
598
+ {"namespace": "shop", "owner_kind": "Deployment", "owner_name": "web", "container": "app",
599
+ "last_hour": "2026-11-21T09:00:00Z", "namespace_opted_in": True, "setting_status": "manifest_raw",
600
+ "current": {"request_units": None, "limit_units": None, "request_mcpu": 500, "limit_mcpu": 1000},
601
+ "observed": obs, "recommendation": rec_ok, "clipped": True, "limit_bound_share": 0.08},
602
+ {"namespace": "jobs", "owner_kind": "StatefulSet", "owner_name": "db", "container": "pg",
603
+ "last_hour": "2026-11-21T09:00:00Z", "namespace_opted_in": True, "setting_status": "manifest_units",
604
+ "current": {"request_units": 100, "limit_units": 200, "request_mcpu": None, "limit_mcpu": None},
605
+ "observed": obs, "recommendation": rec_wait, "clipped": False, "limit_bound_share": 0.0}]}
606
+
607
+
608
+ def test_cpu_sizing_table(monkeypatch):
609
+ r, calls, _ = run(["cpu-sizing", "412"], [reply(200, cpu_sizing_body())], monkeypatch)
610
+ assert r.exit_code == 0, r.output
611
+ assert calls[0][:2] == ("GET", f"{BASE}/pools/412/cpu-sizing")
612
+ assert not calls[0][2].get("params")
613
+ lines = r.stdout.splitlines()
614
+ assert lines[0].split()[:2] == ["WORKLOAD", "CONTAINER"]
615
+ assert "shop/Deployment/web" in lines[1] and "500/1000m" in lines[1] and "230/600u" in lines[1]
616
+ assert lines[1].rstrip().endswith("yes")
617
+ assert "100/200u" in lines[2] and "wait (9/72h)" in lines[2]
618
+
619
+
620
+ def test_cpu_sizing_sends_the_api_query_names(monkeypatch):
621
+ r, calls, _ = run(["cpu-sizing", "412", "--namespace", "shop", "--owner-kind", "Deployment",
622
+ "--window-days", "30", "--clipped-only"], [reply(200, cpu_sizing_body())], monkeypatch)
623
+ assert r.exit_code == 0, r.output
624
+ assert calls[0][2]["params"] == {"namespace": "shop", "owner_kind": "Deployment", "window_days": 30,
625
+ "clipped_only": "true"}
626
+
627
+
628
+ def test_cpu_sizing_window_is_bounded(monkeypatch):
629
+ r, calls, _ = run(["cpu-sizing", "412", "--window-days", "36"], [reply(200, cpu_sizing_body())], monkeypatch)
630
+ assert r.exit_code != 0 and calls == []
631
+
632
+
633
+ def test_cpu_sizing_json_is_the_raw_body(monkeypatch):
634
+ r, _, _ = run(["cpu-sizing", "412", "--json"], [reply(200, cpu_sizing_body())], monkeypatch)
635
+ assert r.exit_code == 0, r.output
636
+ assert json.loads(r.stdout) == cpu_sizing_body()
637
+
638
+
639
+ def test_cpu_sizing_history(monkeypatch):
640
+ body = {"pool_id": 412, "namespace": "shop", "owner_kind": "Deployment", "owner_name": "web", "window_days": 2,
641
+ "generated_at": "2026-11-21T10:00:00Z", "containers": [
642
+ {"container": "app", "clipped": True, "limit_bound_share": 0.08,
643
+ "recommendation": {"status": "ok", "window_days": 14, "qualifying_hours": 120,
644
+ "required_hours": 72, "request_units": 230, "limit_units": 600},
645
+ "points": [{"hour": "2026-11-21T09:00:00Z", "samples": 120, "avg_units": 150, "p95_units": 200,
646
+ "max_units": 500, "request_units": None, "limit_units": None}]}]}
647
+ r, calls, _ = run(["cpu-sizing-history", "412", "shop", "Deployment", "web", "--window-days", "2"],
648
+ [reply(200, body)], monkeypatch)
649
+ assert r.exit_code == 0, r.output
650
+ assert calls[0][:2] == ("GET", f"{BASE}/pools/412/cpu-sizing/workloads/shop/Deployment/web/history")
651
+ assert calls[0][2]["params"] == {"window_days": 2}
652
+ assert "Container app: recommended 230/600u, CLIPPED" in r.stdout
653
+ assert "2026-11-21T09:00:00Z" in r.stdout
@@ -53,7 +53,7 @@ def test_newer_version_prints_one_line(cache, pypi):
53
53
  err = TtyErr()
54
54
  version_check.notify(current="0.8.0", err=err, now=1000.0)
55
55
  assert err.getvalue() == f"mctl 0.9.0 is available (you have 0.8.0). Upgrade: {UPGRADE}\n"
56
- assert pypi["calls"] == [("GET", "https://pypi.org/pypi/multicloud-cli/json", 1)]
56
+ assert pypi["calls"] == [("GET", "https://pypi.org/pypi/multicloud-cli/json", (1, 1))]
57
57
  assert json.loads(cache.read_text()) == {"checked_at": 1000.0, "latest": "0.9.0"}
58
58
 
59
59
 
@@ -1 +0,0 @@
1
- __version__ = "0.12.0"
@@ -1,24 +0,0 @@
1
- """Every request carries User-Agent: mctl/<version>, and the package has one version."""
2
- import requests
3
-
4
- from multicloud_cli import __version__, net
5
-
6
-
7
- def test_user_agent_is_added_and_headers_are_kept(monkeypatch):
8
- seen = {}
9
- monkeypatch.setattr(requests, "request", lambda m, u, **kw: seen.update(kw) or "r")
10
- assert net.request("GET", "https://x", headers={"X-API-Key": "k"}, timeout=1) == "r"
11
- assert seen["headers"] == {"User-Agent": f"mctl/{__version__}", "X-API-Key": "k"}
12
- net.request("POST", "https://x", data={"a": "b"})
13
- assert seen["headers"] == {"User-Agent": f"mctl/{__version__}"}
14
-
15
-
16
- def test_no_module_calls_requests_directly():
17
- # A direct requests call would skip the User-Agent header; only net.py may make one.
18
- import pathlib
19
- import re
20
- pkg = pathlib.Path(net.__file__).parent
21
- hits = [f"{p.name}:{i}" for p in sorted(pkg.glob("*.py")) if p.name != "net.py"
22
- for i, line in enumerate(p.read_text(encoding="utf-8").splitlines(), 1)
23
- if re.search(r"\brequests\.(request|get|post|put|patch|delete|head|Session)\(", line)]
24
- assert hits == []
File without changes