multicloud-cli 0.11.0__tar.gz → 0.13.0__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 (46) hide show
  1. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/PKG-INFO +3 -1
  2. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/README.md +2 -0
  3. multicloud_cli-0.13.0/multicloud_cli/__init__.py +1 -0
  4. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/api.py +16 -8
  5. multicloud_cli-0.13.0/multicloud_cli/db_access.py +162 -0
  6. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/extend.py +119 -1
  7. multicloud_cli-0.13.0/multicloud_cli/kube.py +89 -0
  8. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/main.py +2 -0
  9. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/net.py +17 -6
  10. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/pool.py +73 -0
  11. multicloud_cli-0.13.0/tests/test_db_access.py +285 -0
  12. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_pool.py +94 -0
  13. multicloud_cli-0.13.0/tests/test_proxy_key.py +228 -0
  14. multicloud_cli-0.11.0/multicloud_cli/__init__.py +0 -1
  15. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/.gitignore +0 -0
  16. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/LICENSE +0 -0
  17. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/account.py +0 -0
  18. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/auth.py +0 -0
  19. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/catalog.py +0 -0
  20. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/cloud_account.py +0 -0
  21. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/config.py +0 -0
  22. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/duration.py +0 -0
  23. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/exitcodes.py +0 -0
  24. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/node.py +0 -0
  25. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/orgopt.py +0 -0
  26. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/output.py +0 -0
  27. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/ssh.py +0 -0
  28. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/ssh_cert.py +0 -0
  29. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/sso.py +0 -0
  30. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/multicloud_cli/version_check.py +0 -0
  31. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/pyproject.toml +0 -0
  32. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/__init__.py +0 -0
  33. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/conftest.py +0 -0
  34. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/helpers.py +0 -0
  35. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_account_extend.py +0 -0
  36. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_apply.py +0 -0
  37. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_auth.py +0 -0
  38. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_catalog.py +0 -0
  39. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_cloud_account.py +0 -0
  40. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_conventions.py +0 -0
  41. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_net.py +0 -0
  42. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_ssh.py +0 -0
  43. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_ssh_cert.py +0 -0
  44. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_sso.py +0 -0
  45. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_sso_session.py +0 -0
  46. {multicloud_cli-0.11.0 → multicloud_cli-0.13.0}/tests/test_version_check.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: multicloud-cli
3
- Version: 0.11.0
3
+ Version: 0.13.0
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>
@@ -84,6 +84,7 @@ mctl cloud-account verify 7 --wait
84
84
  | `mctl cloud-account list` / `show <id> [--json]` | The connections of your organization. |
85
85
  | `mctl overview` / `billing` | Setup checklist, alerts and pool counts; payment gate status. Read access or a member sign-in. |
86
86
  | `mctl extend create NAME` | Make an Extend pool. Owner sign-in only. |
87
+ | `mctl extend proxy-key create --pool POOL --kube-context CTX` | Make the `extend:proxy` key of the Extend proxy and write it to its Secret with kubectl. Never prints the key. Owner sign-in only. |
87
88
  | `mctl peering create\|list\|show\|revoke POOL ...` | Manage the peerings of an Extend pool. Owner sign-in only. |
88
89
  | `mctl ssh allow\|list\|revoke`, `mctl node list`, `mctl ssh NODE [-y] [-- ssh args]` | Operators (role `multicloud-admins`): open tcp/22 on a node for your own IPv4 address, list the nodes and the grants, connect. Organization owners: `mctl ssh NODE` logs in to a node of your pool with a 30-minute certificate. Details: `mctl ssh --help`. |
89
90
  | `mctl ssh support allow --pool POOL [--for 4h]`, `support list`, `support revoke ID` | Organization owner: let Multicloud support log in to one pool for up to 7 days, see the consents and the certificates issued, end a consent. A support certificate already issued stays valid up to 30 minutes after a revoke. |
@@ -157,6 +158,7 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
157
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. |
158
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. |
159
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. |
160
162
  | `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
161
163
  | `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`. |
162
164
  | `mctl pool rotate-credentials <pool>` / `rotation-status <pool>` | Renew the pool's access credentials; show the progress of the last renewal. |
@@ -53,6 +53,7 @@ mctl cloud-account verify 7 --wait
53
53
  | `mctl cloud-account list` / `show <id> [--json]` | The connections of your organization. |
54
54
  | `mctl overview` / `billing` | Setup checklist, alerts and pool counts; payment gate status. Read access or a member sign-in. |
55
55
  | `mctl extend create NAME` | Make an Extend pool. Owner sign-in only. |
56
+ | `mctl extend proxy-key create --pool POOL --kube-context CTX` | Make the `extend:proxy` key of the Extend proxy and write it to its Secret with kubectl. Never prints the key. Owner sign-in only. |
56
57
  | `mctl peering create\|list\|show\|revoke POOL ...` | Manage the peerings of an Extend pool. Owner sign-in only. |
57
58
  | `mctl ssh allow\|list\|revoke`, `mctl node list`, `mctl ssh NODE [-y] [-- ssh args]` | Operators (role `multicloud-admins`): open tcp/22 on a node for your own IPv4 address, list the nodes and the grants, connect. Organization owners: `mctl ssh NODE` logs in to a node of your pool with a 30-minute certificate. Details: `mctl ssh --help`. |
58
59
  | `mctl ssh support allow --pool POOL [--for 4h]`, `support list`, `support revoke ID` | Organization owner: let Multicloud support log in to one pool for up to 7 days, see the consents and the certificates issued, end a consent. A support certificate already issued stays valid up to 30 minutes after a revoke. |
@@ -126,6 +127,7 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
126
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. |
127
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. |
128
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. |
129
131
  | `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
130
132
  | `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`. |
131
133
  | `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.0"
@@ -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}")
@@ -13,7 +13,7 @@ from urllib.parse import quote
13
13
 
14
14
  import click
15
15
 
16
- from . import api, exitcodes
16
+ from . import api, exitcodes, kube
17
17
  from .cloud_account import quota_lines
18
18
  from .orgopt import org_group, org_option
19
19
  from .output import (collect as _collect, dump as _dump, echo as _echo, json_option, load_body, no_headers_option, quiet_option,
@@ -205,6 +205,124 @@ def show(ctx, pool, peering_id, as_json):
205
205
  click.echo(_peering_readable(data))
206
206
 
207
207
 
208
+ PROXY_NAMESPACE = "multicloud-extend-proxy"
209
+ PROXY_SECRET = "extend-proxy-api-key"
210
+ KEY_ID_ANNOTATION = "multicloud.io/api-key-id"
211
+ KEY_PREFIX_ANNOTATION = "multicloud.io/api-key-prefix"
212
+
213
+
214
+ @extend.group(name="proxy-key", cls=org_group("extend_org"))
215
+ def proxy_key():
216
+ """The API key of the Extend proxy (section 3.9 of the Extend guide)."""
217
+
218
+
219
+ def _sso_call(org, method: str, path: str, **kw) -> Dict[str, Any]:
220
+ # The key routes refuse every API key: use the SSO sign-in even when MULTICLOUD_API_KEY is set.
221
+ try:
222
+ return api.call(method, org, path, prefer_sso=True, **kw)
223
+ except api.ApiError as ex:
224
+ raise _fail(ex)
225
+
226
+
227
+ def _drop_key(org, key_id: str) -> Optional[str]:
228
+ """Revoke, then delete, a key this command made. Returns an error text, or None when both worked."""
229
+ try:
230
+ api.call("POST", org, f"/keys/{quote(key_id, safe='')}/revoke", prefer_sso=True)
231
+ except api.ApiError as ex:
232
+ return f"could not revoke it ({ex})"
233
+ try:
234
+ api.call("DELETE", org, f"/keys/{quote(key_id, safe='')}", accept=(204,), prefer_sso=True)
235
+ except api.ApiError as ex:
236
+ return f"revoked it, could not delete it ({ex})"
237
+ return None
238
+
239
+
240
+ @proxy_key.command(name="create")
241
+ @click.option("--pool", required=True, metavar="POOL", help="The Extend pool name. It names the key only: the key "
242
+ "works for every Extend pool of the organization")
243
+ @click.option("--kube-context", "kube_context", required=True, metavar="CONTEXT",
244
+ help="The kubectl context of the cluster that runs the proxy")
245
+ @click.option("--namespace", default=PROXY_NAMESPACE, show_default=True, help="Namespace of the proxy; it must exist")
246
+ @click.option("--secret", "secret_name", default=PROXY_SECRET, show_default=True, help="Name of the Secret")
247
+ @click.option("--replace", is_flag=True, help="Overwrite an existing Secret with a new key. The old key stays valid "
248
+ "until you revoke it")
249
+ @json_option
250
+ @click.pass_context
251
+ def create_proxy_key(ctx, pool, kube_context, namespace, secret_name, replace, as_json):
252
+ """Create an extend:proxy API key and write it to the proxy Secret (data key "key").
253
+
254
+ The key goes from the API to kubectl standard input only. mctl never prints it, and it is never in a
255
+ command line. Needs kubectl on PATH and an SSO sign-in as an organization owner (mctl auth login).
256
+ """
257
+ def go(org):
258
+ # Every check before the key exists: the rollback below is the rare path.
259
+ kube.require_namespace(kube_context, namespace)
260
+ old_id = kube.secret_annotation(kube_context, namespace, secret_name, KEY_ID_ANNOTATION)
261
+ if old_id is not None and not replace:
262
+ raise ExtendError(f"Secret {namespace}/{secret_name} exists in context {kube_context}. "
263
+ "Nothing was created. To write a new key, run again with --replace.")
264
+ old_prefix = (kube.secret_annotation(kube_context, namespace, secret_name, KEY_PREFIX_ANNOTATION)
265
+ if old_id is not None else None)
266
+ _sso_call(org, "GET", _pool_path(pool)) # the pool exists and you are its owner
267
+ try:
268
+ made = api.call("POST", org, "/keys", prefer_sso=True, body={
269
+ "name": f"extend-proxy-{pool}"[:256],
270
+ "description": f"Extend proxy, Secret {namespace}/{secret_name}, kubectl context {kube_context}"[:1000],
271
+ "scopes": ["extend:proxy"]})
272
+ except api.ApiError as ex:
273
+ if ex.status is None or ex.status >= 500:
274
+ raise _fail(ex, f"{ex} A key named extend-proxy-{pool} may exist without a Secret. "
275
+ "Check the console (Account, API keys) and revoke it.")
276
+ raise _fail(ex)
277
+ raw, key_id = made.pop("key", None), made.get("id")
278
+ if not raw or not key_id:
279
+ raise ExtendError("The API answer holds no key. Nothing was written.")
280
+ try:
281
+ kube.write_secret(
282
+ kube_context, namespace, secret_name, {"key": raw}, replace=old_id is not None,
283
+ labels={"app.kubernetes.io/name": "extend-proxy", "app.kubernetes.io/managed-by": "mctl"},
284
+ annotations={KEY_ID_ANNOTATION: key_id, KEY_PREFIX_ANNOTATION: str(made.get("key_prefix") or "")})
285
+ except kube.KubeTimeout as ex:
286
+ # The write may have landed: read the Secret back before a rollback could revoke the key it holds.
287
+ try:
288
+ landed = kube.secret_annotation(kube_context, namespace, secret_name, KEY_ID_ANNOTATION) == key_id
289
+ except kube.KubeError:
290
+ raise ExtendError(f"{ex} The Secret may hold the new key {made.get('key_prefix')} (id {key_id}). "
291
+ f"Check the annotation {KEY_ID_ANNOTATION} of Secret {namespace}/{secret_name}; "
292
+ "if it shows another id, revoke the new key in the console: Account, API keys.")
293
+ if not landed:
294
+ problem = _drop_key(org, key_id)
295
+ raise ExtendError(f"{ex} The Secret is unchanged. The new key {made.get('key_prefix')} "
296
+ + ("was revoked and deleted." if problem is None else
297
+ f"(id {key_id}): {problem}. Revoke it in the console: Account, API keys."))
298
+ except BaseException as ex: # also Ctrl-C: a key that reached no Secret must not stay valid
299
+ interrupted = isinstance(ex, KeyboardInterrupt)
300
+ first = "Interrupted." if interrupted else str(ex)
301
+ code = exitcodes.INTERRUPTED if interrupted else exitcodes.ERROR
302
+ problem = _drop_key(org, key_id)
303
+ if problem is None:
304
+ state = "" if interrupted else " The Secret is unchanged."
305
+ raise ExtendError(f"{first}{state} The new key {made.get('key_prefix')} was revoked and deleted.",
306
+ code)
307
+ raise ExtendError(f"{first} The new key {made.get('key_prefix')} (id {key_id}): {problem}. "
308
+ "Revoke it in the console: Account, API keys.", code)
309
+ return {"id": key_id, "key_prefix": made.get("key_prefix"), "name": made.get("name"),
310
+ "scopes": made.get("scopes"), "kube_context": kube_context, "namespace": namespace,
311
+ "secret": secret_name, "replaced": old_id is not None, "replaced_key_id": old_id or None,
312
+ "replaced_key_prefix": old_prefix or None}
313
+ out = run(ctx.obj.get("extend_org"), go, (ExtendError, api.ApiError, kube.KubeError))
314
+ if as_json:
315
+ return _dump(out)
316
+ click.echo(f"Key {out['key_prefix']} ({out['name']}) written to Secret {namespace}/{secret_name} "
317
+ f"in context {kube_context}.")
318
+ click.echo("The key works for every Extend pool of the organization.")
319
+ if out["replaced"]:
320
+ old = " ".join(p for p in (out["replaced_key_prefix"], out["replaced_key_id"] and f"(id {out['replaced_key_id']})")
321
+ if p)
322
+ click.echo(f"Next: kubectl --context {kube_context} -n {namespace} rollout restart deployment")
323
+ click.echo(f"Then revoke the old key{' ' + old if old else ''} in the console: Account, API keys.")
324
+
325
+
208
326
  @peering.command(name="revoke")
209
327
  @click.argument("pool", metavar="POOL")
210
328
  @click.argument("peering_id", metavar="ID", type=click.IntRange(min=1))
@@ -0,0 +1,89 @@
1
+ """Small kubectl helpers: write a secret value to a Kubernetes Secret without putting it on a command line.
2
+
3
+ ``mctl`` runs the ``kubectl`` that is on PATH, with the ``--context`` the user names. A secret value goes to
4
+ ``kubectl`` only on standard input, never in argv (``ps`` shows argv to every local user) and never in an
5
+ ``-o yaml``/``-o json`` read. The Secret is written with ``create`` or ``replace``, not ``apply``: ``apply`` copies
6
+ the whole object, the value included, into the ``last-applied-configuration`` annotation.
7
+ """
8
+ import json
9
+ import shutil
10
+ import subprocess
11
+ from typing import Dict, List, Optional
12
+
13
+ from . import exitcodes
14
+
15
+ TIMEOUT_S = 60
16
+
17
+
18
+ class KubeError(exitcodes.CliError):
19
+ pass
20
+
21
+
22
+ class KubeTimeout(KubeError):
23
+ """kubectl did not answer: the change may or may not have reached the cluster."""
24
+
25
+
26
+ def _redact(text: str, secrets: List[str]) -> str:
27
+ for s in secrets:
28
+ if s:
29
+ text = text.replace(s, "<redacted>")
30
+ return text.strip()
31
+
32
+
33
+ def kubectl(context: str, args: List[str], stdin: Optional[str] = None,
34
+ secrets: List[str] = ()) -> subprocess.CompletedProcess:
35
+ """Run ``kubectl --context CONTEXT ARGS``. ``stdin`` is the only way a secret value reaches kubectl."""
36
+ tool = shutil.which("kubectl")
37
+ if not tool:
38
+ raise KubeError("kubectl is not on PATH. Install it, or run this command where kubectl reaches your cluster.")
39
+ argv = [tool, "--context", context, *args]
40
+ try:
41
+ return subprocess.run(argv, input=stdin, capture_output=True, text=True, timeout=TIMEOUT_S)
42
+ except subprocess.TimeoutExpired:
43
+ raise KubeTimeout(f"kubectl did not answer in {TIMEOUT_S} s (context {context}).")
44
+ except OSError as ex:
45
+ raise KubeError(f"Could not run kubectl: {_redact(str(ex), list(secrets))}")
46
+
47
+
48
+ def _fail(done: subprocess.CompletedProcess, what: str, secrets: List[str] = ()) -> KubeError:
49
+ text = _redact(done.stderr or done.stdout or f"exit code {done.returncode}", list(secrets))
50
+ return KubeError(f"{what}: {text}")
51
+
52
+
53
+ def require_namespace(context: str, namespace: str) -> None:
54
+ """Fail unless the context answers and the namespace exists."""
55
+ done = kubectl(context, ["get", "namespace", namespace, "-o", "name"])
56
+ if done.returncode == 0:
57
+ return
58
+ if "NotFound" in (done.stderr or ""):
59
+ raise KubeError(f"Namespace {namespace} does not exist in context {context}.")
60
+ raise _fail(done, f"Could not read namespace {namespace} in context {context}")
61
+
62
+
63
+ def secret_annotation(context: str, namespace: str, name: str, annotation: str) -> Optional[str]:
64
+ """None when the Secret does not exist; else the value of one annotation ("" when it has none).
65
+ Reads only the name and the annotation, never the data."""
66
+ path = annotation.replace(".", "\\.")
67
+ done = kubectl(context, ["-n", namespace, "get", "secret", name, "--ignore-not-found",
68
+ "-o", "jsonpath={.metadata.name}{\"\\t\"}{.metadata.annotations." + path + "}"])
69
+ if done.returncode != 0:
70
+ raise _fail(done, f"Could not read Secret {namespace}/{name}")
71
+ if not done.stdout.strip():
72
+ return None
73
+ return done.stdout.split("\t", 1)[1].strip() if "\t" in done.stdout else ""
74
+
75
+
76
+ def write_secret(context: str, namespace: str, name: str, data: Dict[str, str], *,
77
+ replace: bool = False, labels: Optional[Dict[str, str]] = None,
78
+ annotations: Optional[Dict[str, str]] = None) -> None:
79
+ """Create the Secret, or with ``replace`` overwrite it. Without ``replace`` an existing Secret makes it fail:
80
+ ``kubectl create`` refuses atomically, so nothing written between a check and this call is lost."""
81
+ manifest = {"apiVersion": "v1", "kind": "Secret", "type": "Opaque",
82
+ "metadata": {"name": name, "namespace": namespace, "labels": labels or {},
83
+ "annotations": annotations or {}},
84
+ "stringData": data}
85
+ secrets = list(data.values())
86
+ verb = "replace" if replace else "create"
87
+ done = kubectl(context, ["-n", namespace, verb, "-f", "-"], stdin=json.dumps(manifest), secrets=secrets)
88
+ if done.returncode != 0:
89
+ raise _fail(done, f"Could not write Secret {namespace}/{name}", secrets)
@@ -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
 
@@ -39,14 +39,25 @@ class IPv4Adapter(HTTPAdapter):
39
39
  super().init_poolmanager(connections, maxsize, block, **pool_kwargs)
40
40
 
41
41
 
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."""
42
+ class IPv6Adapter(HTTPAdapter):
43
+ """Connects over IPv6 only. Binding the local end to ``::`` makes urllib3 skip every IPv4 (A) address: its socket
44
+ cannot bind there, so the next address is tried. A host with no IPv6 route ends in a ``ConnectionError``."""
45
+
46
+ def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
47
+ pool_kwargs["source_address"] = ("::", 0)
48
+ super().init_poolmanager(connections, maxsize, block, **pool_kwargs)
49
+
50
+
51
+ def request(method: str, url: str, ipv4_only: bool = False, ipv6_only: bool = False,
52
+ **kw: Any) -> requests.Response:
53
+ """One request. ``ipv4_only`` / ``ipv6_only`` connect over one address family only: the grant routes read the
54
+ address of the caller as the API sees it, and ``api.multicloud.io`` has A and AAAA records."""
45
55
  kw["headers"] = {"User-Agent": USER_AGENT, **(kw.get("headers") or {})}
46
- if ipv4_only:
56
+ if ipv4_only or ipv6_only:
57
+ adapter = IPv6Adapter if ipv6_only else IPv4Adapter
47
58
  with requests.Session() as session:
48
- session.mount("https://", IPv4Adapter())
49
- session.mount("http://", IPv4Adapter())
59
+ session.mount("https://", adapter())
60
+ session.mount("http://", adapter())
50
61
  r = session.request(method, url, **kw)
51
62
  else:
52
63
  r = requests.request(method, url, **kw)
@@ -199,6 +199,79 @@ 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
+
202
275
  def _json_value(ctx, param, value):
203
276
  """A JSON value, or ``@path`` to read it from a file (``@-``: standard input)."""
204
277
  if value is None: