multicloud-cli 0.13.1__tar.gz → 0.14.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.13.1 → multicloud_cli-0.14.0}/PKG-INFO +8 -2
  2. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/README.md +7 -1
  3. multicloud_cli-0.14.0/multicloud_cli/__init__.py +1 -0
  4. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/cloud_account.py +45 -1
  5. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/db_access.py +8 -1
  6. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/pool.py +266 -3
  7. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/ssh.py +42 -14
  8. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/ssh_cert.py +7 -4
  9. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_cloud_account.py +59 -0
  10. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_db_access.py +9 -0
  11. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_pool.py +223 -0
  12. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_ssh.py +36 -0
  13. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_ssh_cert.py +9 -0
  14. multicloud_cli-0.13.1/multicloud_cli/__init__.py +0 -1
  15. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/.gitignore +0 -0
  16. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/LICENSE +0 -0
  17. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/account.py +0 -0
  18. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/api.py +0 -0
  19. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/auth.py +0 -0
  20. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/catalog.py +0 -0
  21. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/config.py +0 -0
  22. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/duration.py +0 -0
  23. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/exitcodes.py +0 -0
  24. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/extend.py +0 -0
  25. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/kube.py +0 -0
  26. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/main.py +0 -0
  27. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/net.py +0 -0
  28. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/node.py +0 -0
  29. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/orgopt.py +0 -0
  30. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/output.py +0 -0
  31. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/sso.py +0 -0
  32. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/multicloud_cli/version_check.py +0 -0
  33. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/pyproject.toml +0 -0
  34. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/__init__.py +0 -0
  35. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/conftest.py +0 -0
  36. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/helpers.py +0 -0
  37. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_account_extend.py +0 -0
  38. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_apply.py +0 -0
  39. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_auth.py +0 -0
  40. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_catalog.py +0 -0
  41. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_conventions.py +0 -0
  42. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_net.py +0 -0
  43. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_proxy_key.py +0 -0
  44. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_sso.py +0 -0
  45. {multicloud_cli-0.13.1 → multicloud_cli-0.14.0}/tests/test_sso_session.py +0 -0
  46. {multicloud_cli-0.13.1 → multicloud_cli-0.14.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.13.1
3
+ Version: 0.14.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>
@@ -55,7 +55,7 @@ OpenTofu or Terraform 1.10 or later.
55
55
  ```bash
56
56
  mctl auth login # opens your browser; sign in as you do on multicloud.io
57
57
  mkdir multicloud-aws && cd multicloud-aws
58
- mctl cloud-account create --cloud AWS --account 123456789012 --region us-east-1
58
+ mctl cloud-account create --cloud AWS --account 123456789012 # every region; add --region to limit
59
59
  export AWS_REGION=us-east-1 # Terraform needs a region when your AWS profile has none
60
60
  mctl cloud-account apply 7 # init, plan, asks you, apply, then waits for "Ready"
61
61
  ```
@@ -161,6 +161,12 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
161
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
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
163
  | `mctl pool cpu-sizing-history <pool> <namespace> <owner-kind> <owner-name>` | The hourly cpu-units of one workload, per container. `--window-days`, `--json`. |
164
+ | `mctl pool cpu-units-mode <pool>` | The cpu-units Auto mode (advise, selected, full). `--preview MODE` shows the change list; `--set MODE` shows it, asks, then applies it (`--yes` skips the question). `--convert-raw`, `--json`. Write access for `--set`. |
165
+ | `mctl pool cpu-units-select <pool> <namespace> <owner-kind> <owner-name>` | Choose how Auto treats one workload: follow (default), `--pin CONTAINER=UNITS[:LIMIT]` (repeat), or `--exclude`. `--convert-raw`, `--startup-units N`, `--json`. |
166
+ | `mctl pool cpu-units-unselect <pool> <namespace> <owner-kind> <owner-name>` | Remove the selection. In `selected` the workload leaves Auto; in `full` it follows the recommendation. |
167
+ | `mctl pool cpu-units-roll <pool> <namespace> <owner-kind> <owner-name>` | Roll now: evict the pods of one workload one at a time, so the new pods get the Auto value. Asks first (`--yes` skips it). `--allow-downtime` for a 1-replica workload, `--json`. Write access. |
168
+ | `mctl pool cpu-units-rolls <pool>` | The active Roll now requests (`--all`: finished ones too), `--json`. |
169
+ | `mctl pool cpu-units-roll-cancel <pool> <roll-id>` | Cancel a roll before its next eviction, `--json`. Write access. |
164
170
  | `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
165
171
  | `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`. |
166
172
  | `mctl pool rotate-credentials <pool>` / `rotation-status <pool>` | Renew the pool's access credentials; show the progress of the last renewal. |
@@ -24,7 +24,7 @@ OpenTofu or Terraform 1.10 or later.
24
24
  ```bash
25
25
  mctl auth login # opens your browser; sign in as you do on multicloud.io
26
26
  mkdir multicloud-aws && cd multicloud-aws
27
- mctl cloud-account create --cloud AWS --account 123456789012 --region us-east-1
27
+ mctl cloud-account create --cloud AWS --account 123456789012 # every region; add --region to limit
28
28
  export AWS_REGION=us-east-1 # Terraform needs a region when your AWS profile has none
29
29
  mctl cloud-account apply 7 # init, plan, asks you, apply, then waits for "Ready"
30
30
  ```
@@ -130,6 +130,12 @@ mctl pool wake ci --wait --timeout 15m # exit 0 ready, 5 timeout, 6
130
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
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
132
  | `mctl pool cpu-sizing-history <pool> <namespace> <owner-kind> <owner-name>` | The hourly cpu-units of one workload, per container. `--window-days`, `--json`. |
133
+ | `mctl pool cpu-units-mode <pool>` | The cpu-units Auto mode (advise, selected, full). `--preview MODE` shows the change list; `--set MODE` shows it, asks, then applies it (`--yes` skips the question). `--convert-raw`, `--json`. Write access for `--set`. |
134
+ | `mctl pool cpu-units-select <pool> <namespace> <owner-kind> <owner-name>` | Choose how Auto treats one workload: follow (default), `--pin CONTAINER=UNITS[:LIMIT]` (repeat), or `--exclude`. `--convert-raw`, `--startup-units N`, `--json`. |
135
+ | `mctl pool cpu-units-unselect <pool> <namespace> <owner-kind> <owner-name>` | Remove the selection. In `selected` the workload leaves Auto; in `full` it follows the recommendation. |
136
+ | `mctl pool cpu-units-roll <pool> <namespace> <owner-kind> <owner-name>` | Roll now: evict the pods of one workload one at a time, so the new pods get the Auto value. Asks first (`--yes` skips it). `--allow-downtime` for a 1-replica workload, `--json`. Write access. |
137
+ | `mctl pool cpu-units-rolls <pool>` | The active Roll now requests (`--all`: finished ones too), `--json`. |
138
+ | `mctl pool cpu-units-roll-cancel <pool> <roll-id>` | Cancel a roll before its next eviction, `--json`. Write access. |
133
139
  | `mctl pool hibernate <pool>` / `wake <pool>` | Pause or resume a pool. |
134
140
  | `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`. |
135
141
  | `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.14.0"
@@ -314,7 +314,7 @@ def _file_exists(name: str):
314
314
  @click.option("--new-account-email", "new_email", metavar="EMAIL",
315
315
  help="AWS: create a new AWS account for Multicloud in your AWS Organizations, with this email "
316
316
  "(not allowed with --account)")
317
- @click.option("--region", "regions", multiple=True, help="Region to allow; repeat for several")
317
+ @click.option("--region", "regions", multiple=True, help="Region to allow; repeat for several (default: every region)")
318
318
  @click.option("--force", is_flag=True, help="Overwrite an existing multicloud.tf")
319
319
  @click.option("--opt-in-regions/--no-opt-in-regions", "opt_in", default=None,
320
320
  help="AWS: turn on the opt-in regions of the account that are off (default: yes; "
@@ -537,6 +537,7 @@ def _readable(data: Dict[str, Any]) -> str:
537
537
  f"Status: {status}",
538
538
  ("Account", data.get("native_id") or data.get("expected_native_id")),
539
539
  ("Regions", ", ".join(regions) if regions else "all"),
540
+ ("Pending regions", ", ".join(data.get("regions_pending") or [])),
540
541
  ("Opt-in regions", None if data.get("enable_opt_in_regions") is None
541
542
  else "turn on" if data["enable_opt_in_regions"] else "leave off"),
542
543
  ("Role", data.get("role_arn")),
@@ -862,6 +863,49 @@ def quota_request(ctx, account_id, region, code, desired, confirm_denied, as_jso
862
863
  sys.exit(exitcodes.ERROR)
863
864
 
864
865
 
866
+ @cloud_account.command(name="set-regions")
867
+ @click.argument("account_id", type=int)
868
+ @click.argument("regions", nargs=-1)
869
+ @click.option("--all", "every", is_flag=True, help="Allow every region of the cloud")
870
+ @json_option
871
+ @click.pass_context
872
+ def set_regions(ctx, account_id, regions, every, as_json):
873
+ """Add or remove regions of a cloud account: set-regions ID (--all | REGION...).
874
+
875
+ REGION... is the new full list: a region the account has now and the list lacks is removed (refused with
876
+ REGIONS_IN_USE when a pool would keep no region). GCE and Azure: applied at once. AWS: a removal applies at
877
+ once; an added region is pending until the role allows it. The answer prints the step to run: put the
878
+ regions of the snippet into multicloud.tf, then 'mctl cloud-account apply ID' (it applies the module with a
879
+ new connect token and verifies), or update the CloudFormation stack; a verify moves each region that passes
880
+ into the account. After a removal the step is optional: it only tightens the role."""
881
+ names = list(dict.fromkeys(r.strip() for r in regions if r.strip()))
882
+ if every == bool(names):
883
+ raise click.UsageError("Give --all, or one or more REGION names, not both and not neither.")
884
+ answer = _run(ctx, lambda org: call("PUT", org, f"/{account_id}/regions",
885
+ body={"regions": None if every else names}))
886
+ if as_json:
887
+ _dump(answer)
888
+ return
889
+ current = answer.get("regions")
890
+ lines = [f"Cloud account {account_id} regions: {', '.join(current) if current else 'all'}"]
891
+ pending = answer.get("regions_pending") or []
892
+ if pending:
893
+ lines.append(f"Pending (the role does not allow them yet): {', '.join(pending)}")
894
+ apply_step = answer.get("apply") or {}
895
+ if apply_step.get("terraform"):
896
+ # `apply` applies multicloud.tf as it is (it does not render the regions) and verifies after the apply.
897
+ command = apply_step.get("command") or f"mctl cloud-account apply {account_id}"
898
+ optional = "" if pending else " Optional: it only tightens the role; the removal is already in force."
899
+ lines.append("First set `regions` in multicloud.tf to the list in the snippet below (the snippet is "
900
+ f"for reference).\nRun: {command} (it applies the module with the new regions and "
901
+ f"verifies){optional}\n{apply_step['terraform'].rstrip()}")
902
+ if apply_step.get("cloudformation"):
903
+ then = ("Optional: it only tightens the role; the removal is already in force." if not pending
904
+ else f"Then run: mctl cloud-account verify {account_id}")
905
+ lines.append(f"{apply_step['cloudformation']} {then}")
906
+ click.echo("\n".join(lines))
907
+
908
+
865
909
  WAIT_DEFAULT = "130m" # the cleanup job gives up after about two hours
866
910
  WAIT_INTERVAL = 30
867
911
 
@@ -80,13 +80,20 @@ def db_access():
80
80
  @click.option("--ttl", "ttl", default="12h", show_default=True, callback=duration_option,
81
81
  help="How long the access lasts: 5m to 24h (30m, 12h, 90s)")
82
82
  @click.option("--ipv4-only", is_flag=True, help="Open only your IPv4 address (use it on a shared network)")
83
+ @click.option("--reason", default=None, metavar="TEXT", help="Why you open DB access (audit log)")
84
+ @click.option("--ticket", default=None, metavar="REF", help="Support ticket of this action (audit log)")
83
85
  @json_option
84
- def allow(ttl, ipv4_only, as_json):
86
+ def allow(ttl, ipv4_only, reason, ticket, as_json):
85
87
  """Open DB access for your current public IPs, or extend it."""
86
88
  def go():
87
89
  if not MIN_TTL_S <= ttl <= MAX_TTL_S:
88
90
  raise DbAccessError(f"--ttl must be between 5m and 24h, not {ttl} seconds.", exitcodes.USAGE)
89
91
  body = {"ttl_seconds": ttl}
92
+ # Sent only when given: a new mctl works against a server that does not know the fields yet.
93
+ if reason is not None:
94
+ body["reason"] = reason
95
+ if ticket is not None:
96
+ body["ticket_ref"] = ticket
90
97
  results: List[Dict[str, Any]] = []
91
98
  notes: List[str] = []
92
99
  try:
@@ -373,6 +373,259 @@ def cpu_sizing_history(ctx, pool_ref, namespace, owner_kind, owner_name, window_
373
373
  _echo(_history_text(data))
374
374
 
375
375
 
376
+ # --- cpu-units Auto: mode, preview and per-workload selections ---
377
+
378
+ CPU_UNITS_MODES = click.Choice(["advise", "selected", "full"])
379
+ RESTART_NOTE = "Values apply when pods are created: run kubectl rollout restart <kind>/<name> -n <ns>"
380
+
381
+
382
+ def _wl_path(namespace: str, owner_kind: str, owner_name: str) -> str:
383
+ from urllib.parse import quote
384
+ return "/".join(quote(s, safe="") for s in (namespace, owner_kind, owner_name))
385
+
386
+
387
+ def _cpu_pair(units, limit, req_mcpu=None, lim_mcpu=None) -> str:
388
+ if units is not None or limit is not None:
389
+ return f"{_units(units)}/{_units(limit)}u"
390
+ if req_mcpu is not None or lim_mcpu is not None:
391
+ return f"{_units(req_mcpu)}/{_units(lim_mcpu)}m"
392
+ return "-"
393
+
394
+
395
+ def _mode_line(d: Dict[str, Any]) -> str:
396
+ return f"mode {d.get('mode')}, convert raw requests: {'yes' if d.get('full_convert_raw') else 'no'}"
397
+
398
+
399
+ def _preview_text(d: Dict[str, Any]) -> str:
400
+ cur, tgt = d.get("current") or {}, d.get("target") or {}
401
+ out = [f"Pool {d.get('pool_id')}: {_mode_line(cur)} -> {_mode_line(tgt)} ({d.get('direction')})"]
402
+ rows = []
403
+ for w in d.get("workloads", []):
404
+ name = f"{w.get('namespace')}/{w.get('owner_kind')}/{w.get('owner_name')}"
405
+ for c in w.get("containers", []):
406
+ rows.append((name, str(c.get("container")),
407
+ _cpu_pair(c.get("current_units"), c.get("current_limit_units"),
408
+ c.get("current_request_mcpu"), c.get("current_limit_mcpu"))
409
+ + " -> " + _cpu_pair(c.get("target_units"), c.get("target_limit_units")),
410
+ str(c.get("status"))))
411
+ out.append(_table(("WORKLOAD", "CONTAINER", "CURRENT -> TARGET", "STATUS"), rows, True) if rows
412
+ else "No workload changes.")
413
+ for key, label in (("excluded", "Excluded"), ("released", "Released")):
414
+ names = [f"{w.get('namespace')}/{w.get('owner_kind')}/{w.get('owner_name')}" for w in d.get(key) or []]
415
+ if names:
416
+ out.append(f"{label}: " + ", ".join(names))
417
+ out.append(f"Raw kept: {d.get('raw_kept', 0)}. Raw converted: {d.get('raw_converted', 0)}. "
418
+ f"Waiting for data: {d.get('waiting_for_data', 0)}.")
419
+ return "\n".join(out)
420
+
421
+
422
+ @pool.command(name="cpu-units-mode")
423
+ @click.argument("pool_ref", metavar="POOL")
424
+ @click.option("--preview", "preview_mode", type=CPU_UNITS_MODES, default=None,
425
+ help="Show what a change to this mode would do. Changes nothing")
426
+ @click.option("--set", "set_mode", type=CPU_UNITS_MODES, default=None,
427
+ help="Change the mode: shows the preview, asks, then applies it")
428
+ @click.option("--convert-raw", is_flag=True, default=False, help="With --preview or --set: also convert raw CPU requests")
429
+ @click.option("-y", "--yes", is_flag=True, help="With --set: apply without asking")
430
+ @json_option
431
+ @click.pass_context
432
+ def cpu_units_mode(ctx, pool_ref, preview_mode, set_mode, convert_raw, yes, as_json):
433
+ """Show, preview or set the cpu-units Auto mode of a pool (advise, selected, full).
434
+
435
+ Without options it shows the current mode. --set always fetches the preview first, shows it, and applies
436
+ it only after you confirm (or --yes). It needs Write access."""
437
+ if preview_mode and set_mode:
438
+ raise click.UsageError("Use --preview or --set, not both.")
439
+ if convert_raw and not (preview_mode or set_mode):
440
+ raise click.UsageError("--convert-raw needs --preview or --set.")
441
+ if set_mode and not yes and not _stdin_is_tty():
442
+ click.echo("Error: Refusing to change the mode without confirmation. Run again with --yes.", err=True)
443
+ sys.exit(exitcodes.ERROR)
444
+ target = preview_mode or set_mode
445
+
446
+ def go(org):
447
+ base = f"/pools/{resolve(org, pool_ref)}/cpu-sizing/mode"
448
+ if not target:
449
+ data = _call(org, "GET", base, READ)
450
+ _dump(data) if as_json else click.echo(f"Pool {data.get('pool_id')}: {_mode_line(data)}")
451
+ return 0
452
+ params = {"mode": target, "full_convert_raw": "true" if convert_raw else "false"}
453
+ plan = _call(org, "GET", base + "/preview", READ, params=params)
454
+ if not set_mode:
455
+ _dump(plan) if as_json else click.echo(_preview_text(plan))
456
+ return 0
457
+ if not as_json:
458
+ click.echo(_preview_text(plan))
459
+ if not yes and not click.confirm("Apply this change?", default=False):
460
+ click.echo("Nothing changed.", err=True)
461
+ return exitcodes.ERROR
462
+ body = {"mode": set_mode, "full_convert_raw": convert_raw, "plan_hash": plan.get("plan_hash")}
463
+ try:
464
+ data = api.call("PUT", org, base, body=body, scope=WRITE)
465
+ except api.ApiError as ex:
466
+ if ex.status == 409:
467
+ raise PoolError(f"The plan changed; run again. ({ex})", ex.exit_code)
468
+ raise _fail(ex)
469
+ if as_json:
470
+ _dump(data)
471
+ else:
472
+ click.echo(f"Pool {data.get('pool_id')}: {_mode_line(data)}")
473
+ click.echo(RESTART_NOTE)
474
+ return 0
475
+ sys.exit(_run(ctx, go) or 0)
476
+
477
+
478
+ def _pin(ctx, param, values):
479
+ """``CONTAINER=UNITS[:LIMIT]`` -> {container, units, limit_units}; LIMIT defaults to UNITS."""
480
+ out = []
481
+ for v in values:
482
+ name, sep, rest = v.partition("=")
483
+ units, _, limit = rest.partition(":")
484
+ try:
485
+ u = int(units)
486
+ lim = int(limit) if limit else u
487
+ except ValueError:
488
+ u = lim = 0
489
+ if not name or not sep or u < 1 or lim < 1:
490
+ raise click.BadParameter(f"'{v}' is not CONTAINER=UNITS[:LIMIT] with whole numbers above 0.")
491
+ out.append({"container": name, "units": u, "limit_units": lim})
492
+ return out
493
+
494
+
495
+ @pool.command(name="cpu-units-select")
496
+ @click.argument("pool_ref", metavar="POOL")
497
+ @click.argument("namespace")
498
+ @click.argument("owner_kind", metavar="OWNER_KIND")
499
+ @click.argument("owner_name", metavar="OWNER_NAME")
500
+ @click.option("--pin", "pins", multiple=True, callback=_pin, metavar="CONTAINER=UNITS[:LIMIT]",
501
+ help="Fix the units of a container (repeat per container). LIMIT defaults to UNITS")
502
+ @click.option("--exclude", is_flag=True, default=False, help="Leave this workload alone")
503
+ @click.option("--convert-raw", is_flag=True, default=False, help="Also convert the workload's raw CPU requests")
504
+ @click.option("--startup-units", type=click.IntRange(min=1), default=None, help="Units for the startup phase")
505
+ @json_option
506
+ @click.pass_context
507
+ def cpu_units_select(ctx, pool_ref, namespace, owner_kind, owner_name, pins, exclude, convert_raw, startup_units,
508
+ as_json):
509
+ """Choose how cpu-units Auto treats one workload: follow (default), pinned (--pin) or excluded (--exclude)."""
510
+ if pins and exclude:
511
+ raise click.UsageError("Use --pin or --exclude, not both.")
512
+ body = {"choice": "excluded" if exclude else "pinned" if pins else "follow", "convert_raw": convert_raw,
513
+ "containers": list(pins) if pins else None, "startup_units": startup_units}
514
+
515
+ def go(org):
516
+ return _call(org, "PUT", f"/pools/{resolve(org, pool_ref)}/cpu-sizing/workloads/"
517
+ f"{_wl_path(namespace, owner_kind, owner_name)}/selection", WRITE, body=body)
518
+ data = _run(ctx, go)
519
+ if as_json:
520
+ return _dump(data)
521
+ click.echo(f"{namespace}/{owner_kind}/{owner_name}: {data.get('choice')}")
522
+ click.echo(RESTART_NOTE)
523
+
524
+
525
+ @pool.command(name="cpu-units-unselect")
526
+ @click.argument("pool_ref", metavar="POOL")
527
+ @click.argument("namespace")
528
+ @click.argument("owner_kind", metavar="OWNER_KIND")
529
+ @click.argument("owner_name", metavar="OWNER_NAME")
530
+ @click.pass_context
531
+ def cpu_units_unselect(ctx, pool_ref, namespace, owner_kind, owner_name):
532
+ """Remove the selection of one workload. In selected mode it leaves Auto; in full mode it follows the recommendation."""
533
+ def go(org):
534
+ return _call(org, "DELETE", f"/pools/{resolve(org, pool_ref)}/cpu-sizing/workloads/"
535
+ f"{_wl_path(namespace, owner_kind, owner_name)}/selection", WRITE,
536
+ accept=(200, 204))
537
+ _run(ctx, go)
538
+ click.echo(f"{namespace}/{owner_kind}/{owner_name}: selection removed")
539
+
540
+
541
+ # --- cpu-units Roll now ---
542
+
543
+ def _roll_line(r: Dict[str, Any]) -> str:
544
+ """One line: roll id, workload, state (with the progress and reason), and the last error."""
545
+ state = str(r.get("state"))
546
+ if r.get("pods_total") is not None:
547
+ state += f" ({r.get('pods_rolled', 0)} of {r.get('pods_total')})"
548
+ if r.get("reason"):
549
+ state += f", {r.get('reason')}"
550
+ line = f"Roll {r.get('roll_id')}: {r.get('namespace')}/{r.get('owner_kind')}/{r.get('owner_name')}: {state}"
551
+ return line + (f". {r.get('message')}" if r.get("message") else "")
552
+
553
+
554
+ @pool.command(name="cpu-units-roll")
555
+ @click.argument("pool_ref", metavar="POOL")
556
+ @click.argument("namespace")
557
+ @click.argument("owner_kind", metavar="OWNER_KIND")
558
+ @click.argument("owner_name", metavar="OWNER_NAME")
559
+ @click.option("--allow-downtime", is_flag=True, default=False,
560
+ help="Accept downtime for a workload with 1 replica (it is down until the new pod is Ready)")
561
+ @click.option("-y", "--yes", is_flag=True, help="Roll without asking")
562
+ @json_option
563
+ @click.pass_context
564
+ def cpu_units_roll(ctx, pool_ref, namespace, owner_kind, owner_name, allow_downtime, yes, as_json):
565
+ """Roll now: replace the pods of one workload, one at a time, so the new pods get the Auto value.
566
+
567
+ It evicts the pods through the Eviction API (PDBs apply). The workload object does not change. It asks for
568
+ confirmation first (--yes skips it). Check progress with: mctl pool cpu-units-rolls POOL. Needs Write access."""
569
+ name = f"{namespace}/{owner_kind}/{owner_name}"
570
+ if not yes and not _stdin_is_tty():
571
+ click.echo("Error: Refusing to roll without confirmation. Run again with --yes.", err=True)
572
+ sys.exit(exitcodes.ERROR)
573
+ if not yes and not click.confirm(f"Evict the pods of {name} one at a time?"
574
+ + (" It is down until the new pod is Ready." if allow_downtime else ""),
575
+ default=False):
576
+ click.echo("Nothing changed.", err=True)
577
+ sys.exit(exitcodes.ERROR)
578
+
579
+ def go(org):
580
+ return _call(org, "POST", f"/pools/{resolve(org, pool_ref)}/cpu-sizing/workloads/"
581
+ f"{_wl_path(namespace, owner_kind, owner_name)}/roll", WRITE,
582
+ body={"allow_downtime": allow_downtime})
583
+ data = _run(ctx, go)
584
+ if as_json:
585
+ return _dump(data)
586
+ click.echo(_roll_line(data))
587
+
588
+
589
+ @pool.command(name="cpu-units-rolls")
590
+ @click.argument("pool_ref", metavar="POOL")
591
+ @click.option("--all", "show_all", is_flag=True, default=False, help="Also the finished rolls")
592
+ @json_option
593
+ @click.pass_context
594
+ def cpu_units_rolls(ctx, pool_ref, show_all, as_json):
595
+ """List the Roll now requests of a pool, newest first. Default: the active ones (queued, rolling, blocked)."""
596
+ def go(org):
597
+ return _call(org, "GET", f"/pools/{resolve(org, pool_ref)}/cpu-sizing/rolls", READ,
598
+ params={"state": "all" if show_all else "active"})
599
+ data = _run(ctx, go)
600
+ if as_json:
601
+ return _dump(data)
602
+ items = data.get("items") or []
603
+ if not items:
604
+ click.echo("No rolls." if show_all else "No active rolls. Use --all to list finished ones.")
605
+ return
606
+ click.echo(_table(("ID", "WORKLOAD", "STATE", "PODS", "REASON", "MESSAGE"), [
607
+ (str(r.get("roll_id")), f"{r.get('namespace')}/{r.get('owner_kind')}/{r.get('owner_name')}",
608
+ str(r.get("state")),
609
+ f"{r.get('pods_rolled', 0)}/{r.get('pods_total')}" if r.get("pods_total") is not None else "-",
610
+ str(r.get("reason") or "-"), str(r.get("message") or "")) for r in items], True))
611
+
612
+
613
+ @pool.command(name="cpu-units-roll-cancel")
614
+ @click.argument("pool_ref", metavar="POOL")
615
+ @click.argument("roll_id", type=click.IntRange(min=1))
616
+ @json_option
617
+ @click.pass_context
618
+ def cpu_units_roll_cancel(ctx, pool_ref, roll_id, as_json):
619
+ """Cancel a Roll now request. The roller stops before its next eviction; replaced pods keep their new values."""
620
+ def go(org):
621
+ return _call(org, "DELETE", f"/pools/{resolve(org, pool_ref)}/cpu-sizing/rolls/{roll_id}", WRITE,
622
+ accept=(200, 202))
623
+ data = _run(ctx, go)
624
+ if as_json:
625
+ return _dump(data)
626
+ click.echo(_roll_line(data))
627
+
628
+
376
629
  def _json_value(ctx, param, value):
377
630
  """A JSON value, or ``@path`` to read it from a file (``@-``: standard input)."""
378
631
  if value is None:
@@ -526,6 +779,11 @@ def _settings_body(sets, resets, settings_json) -> Dict[str, Any]:
526
779
  help="Runner classes of the pool; repeat or separate with commas")
527
780
  @click.option("--clouds", callback=_json_value, default=None,
528
781
  help="JSON list of {type, regions, exclude_regions, use} for clouds the pool has (use false turns one cloud off), or @file.json")
782
+ @click.option("--cloud-account", "cloud_accounts", type=int, multiple=True, metavar="ID",
783
+ help="Replace the pool's connected cloud accounts with these (see: mctl cloud-account list). "
784
+ "Repeat for more (one per cloud); an account you leave out is removed (409 ACCOUNT_HAS_NODES "
785
+ "while the pool has nodes on it). Not with --clouds. The API key needs the Infrastructure "
786
+ "(infra) scope")
529
787
  @click.option("--max-servers", type=int, default=None, help="Most nodes the pool may run (1-100)")
530
788
  @click.option("--set", "sets", multiple=True, metavar="NAME=VALUE",
531
789
  help="Set one setting; VALUE is JSON, else a string (a name list may be comma separated); grant.cpu for grant fields. Repeat")
@@ -534,8 +792,8 @@ def _settings_body(sets, resets, settings_json) -> Dict[str, Any]:
534
792
  help="JSON object of settings (null resets one), or @file.json")
535
793
  @json_option
536
794
  @click.pass_context
537
- def update(ctx, pool_ref, spot_policy, cpu_units_requests, max_cost_per_hour, classes_, clouds, max_servers,
538
- sets, resets, settings_json, as_json):
795
+ def update(ctx, pool_ref, spot_policy, cpu_units_requests, max_cost_per_hour, classes_, clouds, cloud_accounts,
796
+ max_servers, sets, resets, settings_json, as_json):
539
797
  """Change a pool. Only the options you give are sent."""
540
798
  if max_servers is not None and not 1 <= max_servers <= 100:
541
799
  raise click.UsageError("--max-servers must be a whole number from 1 to 100.")
@@ -543,13 +801,18 @@ def update(ctx, pool_ref, spot_policy, cpu_units_requests, max_cost_per_hour, cl
543
801
  body = _collect(spot_policy=spot_policy, cpu_units_requests=cpu_units_requests,
544
802
  max_cost_per_hour=max_cost_per_hour, classes=classes_, clouds=clouds,
545
803
  max_servers=max_servers)
804
+ if cloud_accounts:
805
+ if clouds is not None:
806
+ raise click.UsageError("Use --cloud-account or --clouds, not both.")
807
+ body["cloud_accounts"] = [{"id": i} for i in cloud_accounts]
546
808
  if settings:
547
809
  body["settings"] = settings
548
810
  if not body:
549
811
  raise click.UsageError("Give at least one option to change.")
550
812
 
551
813
  def go(org):
552
- return _call(org, "PATCH", f"/pools/{resolve(org, pool_ref)}", WRITE, body=body)
814
+ return _call(org, "PATCH", f"/pools/{resolve(org, pool_ref)}",
815
+ "infra" if "cloud_accounts" in body else WRITE, body=body)
553
816
  data = _run(ctx, go)
554
817
  if as_json:
555
818
  return _dump(data)
@@ -71,6 +71,25 @@ def wait_for_port(ip: str, port: int = PORT, timeout_s: int = WAIT_S, every_s: i
71
71
  _sleep(every_s)
72
72
 
73
73
 
74
+ def reason_options(fn):
75
+ """``--reason`` and ``--ticket`` of an operator action. The server records them in the audit log of the customer
76
+ organization. Each is sent only when given: a new mctl works against a server that does not know them."""
77
+ fn = click.option("--ticket", "ticket", default=None, metavar="REF",
78
+ help="Support ticket of this action (audit log)")(fn)
79
+ return click.option("--reason", "reason", default=None, metavar="TEXT",
80
+ help="Why you do this (audit log)")(fn)
81
+
82
+
83
+ def _why(reason: Optional[str], ticket: Optional[str]) -> Dict[str, str]:
84
+ """The ``reason`` and ``ticket_ref`` body fields that were given."""
85
+ out = {}
86
+ if reason is not None:
87
+ out["reason"] = reason
88
+ if ticket is not None:
89
+ out["ticket_ref"] = ticket
90
+ return out
91
+
92
+
74
93
  def _call(org, method: str, path: str, **kw) -> Dict[str, Any]:
75
94
  """A grant call: always over IPv4."""
76
95
  try:
@@ -157,14 +176,16 @@ def _grant_text(row: Dict[str, Any]) -> str:
157
176
  @click.option("--for", "ttl", default="1h", show_default=True, callback=duration_option,
158
177
  help="How long the rule lasts: 5m to 8h (30m, 1h, 90s)")
159
178
  @click.option("--cluster", default=None, help="Only this cluster (id or slug). Default: all platform clusters")
179
+ @reason_options
160
180
  @json_option
161
181
  @click.pass_context
162
- def allow(ctx, ttl, cluster, as_json):
182
+ def allow(ctx, ttl, cluster, reason, ticket, as_json):
163
183
  """Open tcp/22 for your IP, or extend the grant you have."""
164
184
  def go(org):
165
185
  if not MIN_TTL_S <= ttl <= MAX_TTL_S:
166
186
  raise SshError(f"--for must be between 5m and 8h, not {ttl} seconds.", exitcodes.USAGE)
167
- return _call(org, "POST", "/ssh-access", body={"cluster_id": _cluster_id(org, cluster), "ttl_seconds": ttl})
187
+ return _call(org, "POST", "/ssh-access", body={"cluster_id": _cluster_id(org, cluster), "ttl_seconds": ttl,
188
+ **_why(reason, ticket)})
168
189
  data = _run(ctx, go)
169
190
  if as_json:
170
191
  return _dump(data)
@@ -194,11 +215,13 @@ def list_(ctx, include_expired, as_json, quiet, no_headers):
194
215
 
195
216
  @ssh.command()
196
217
  @click.argument("grant_id", metavar="ID", type=int)
218
+ @reason_options
197
219
  @json_option
198
220
  @click.pass_context
199
- def revoke(ctx, grant_id, as_json):
221
+ def revoke(ctx, grant_id, reason, ticket, as_json):
200
222
  """Revoke a grant. The firewall rule ends within about 2 minutes."""
201
- data = _run(ctx, lambda org: _call(org, "DELETE", f"/ssh-access/{grant_id}"))
223
+ why = _why(reason, ticket)
224
+ data = _run(ctx, lambda org: _call(org, "DELETE", f"/ssh-access/{grant_id}", **({"body": why} if why else {})))
202
225
  if as_json:
203
226
  return _dump(data)
204
227
  click.echo(f"Revoked grant {grant_id}.")
@@ -326,7 +349,8 @@ def _has_remote_command(extra: Tuple[str, ...]) -> bool:
326
349
  return False
327
350
 
328
351
 
329
- def _launch(org, node: Dict[str, Any], extra: Tuple[str, ...], operator: bool) -> None:
352
+ def _launch(org, node: Dict[str, Any], extra: Tuple[str, ...], operator: bool,
353
+ why: Optional[Dict[str, str]] = None) -> None:
330
354
  """Connect. A node of a Kamaji pool logs in with a certificate; every other node as before (execvp)."""
331
355
  if node.get("node_runtime") != KAMAJI:
332
356
  return _exec(node, extra)
@@ -339,7 +363,7 @@ def _launch(org, node: Dict[str, Any], extra: Tuple[str, ...], operator: bool) -
339
363
  for attempt in (1, 2):
340
364
  try:
341
365
  cert = ssh_cert.ensure_cert(org, cluster_id, key, datetime.now(timezone.utc), prefer_sso=operator,
342
- refresh=refresh)
366
+ refresh=refresh, justification=why if operator else None)
343
367
  except api.ApiError as ex:
344
368
  if ex.status == 403 and "no active support consent" in str(ex).lower():
345
369
  raise SshError(f"No active support consent for pool {pool}. Ask the organization owner to run: "
@@ -386,7 +410,9 @@ def _connect_customer(org, node: Dict[str, Any], yes: bool, extra: Tuple[str, ..
386
410
  _launch(org, node, extra, operator=False)
387
411
 
388
412
 
389
- def _connect(org, ref: str, yes: bool, extra: Tuple[str, ...], pool_ref: Optional[str] = None) -> None:
413
+ def _connect(org, ref: str, yes: bool, extra: Tuple[str, ...], pool_ref: Optional[str] = None,
414
+ why: Optional[Dict[str, str]] = None) -> None:
415
+ why = why or {}
390
416
  operator = _is_operator()
391
417
  node = _find_node(org, ref, operator, pool_ref)
392
418
  ip = node.get("public_ip")
@@ -405,10 +431,10 @@ def _connect(org, ref: str, yes: bool, extra: Tuple[str, ...], pool_ref: Optiona
405
431
  best = max(exact, key=_seconds_left)
406
432
  grant_id = best["id"]
407
433
  if _seconds_left(best) <= REFRESH_BELOW_S:
408
- _call(org, "POST", "/ssh-access", body={"cluster_id": cluster_id}) # extends the same grant
434
+ _call(org, "POST", "/ssh-access", body={"cluster_id": cluster_id, **why}) # extends the same grant
409
435
  elif mine and _port_open(ip, PORT):
410
436
  # A grant for all platform clusters, and the port answers: the node is on a platform cluster.
411
- return _launch(org, node, extra, operator=True)
437
+ return _launch(org, node, extra, operator=True, why=why)
412
438
  else:
413
439
  # No grant, or only a grant for all platform clusters and the port is closed (a customer pool node).
414
440
  slug = node.get("cluster_slug") or cluster_id
@@ -420,11 +446,11 @@ def _connect(org, ref: str, yes: bool, extra: Tuple[str, ...], pool_ref: Optiona
420
446
  if not click.confirm(f"Your IP {source} has no SSH access to {slug}. "
421
447
  f"Open tcp/22 for {source} for 1h?", default=True, err=True):
422
448
  raise SshError("You answered no. No SSH access was opened.")
423
- grant_id = _call(org, "POST", "/ssh-access", body={"cluster_id": cluster_id})["id"]
449
+ grant_id = _call(org, "POST", "/ssh-access", body={"cluster_id": cluster_id, **why})["id"]
424
450
  if not wait_for_port(ip, PORT, WAIT_S, WAIT_EVERY_S, note=f"waiting for the firewall rule (grant {grant_id})"):
425
451
  raise SshError(f"tcp/22 on {ip} did not open within {WAIT_S} s (grant {grant_id}). The scheduler applies "
426
452
  f"grants about every minute. Run the command again in a minute.", exitcodes.PENDING)
427
- _launch(org, node, extra, operator=True)
453
+ _launch(org, node, extra, operator=True, why=why)
428
454
 
429
455
 
430
456
  @ssh.command("nodes")
@@ -455,10 +481,12 @@ def nodes_(ctx, pool_ref, as_json, quiet, no_headers):
455
481
  @click.argument("ssh_args", nargs=-1, type=click.UNPROCESSED, metavar="[SSH_ARGS]...")
456
482
  @click.option("-y", "--yes", is_flag=True, help="Open tcp/22 without asking")
457
483
  @click.option("--pool", "pool_ref", default=None, help="Customer: look for the node in this pool only (id or name)")
484
+ @reason_options
458
485
  @click.pass_context
459
- def connect(ctx, node_ref, ssh_args, yes, pool_ref):
460
- """Connect to a node (id or public IP); put the ssh options after --."""
461
- _run(ctx, lambda org: _connect(org, node_ref, yes, ssh_args, pool_ref))
486
+ def connect(ctx, node_ref, ssh_args, yes, pool_ref, reason, ticket):
487
+ """Connect to a node (id or public IP); put the ssh options after --. An operator may add --reason and
488
+ --ticket for the audit log of the customer organization."""
489
+ _run(ctx, lambda org: _connect(org, node_ref, yes, ssh_args, pool_ref, _why(reason, ticket)))
462
490
 
463
491
 
464
492
  # --- support consent ---------------------------------------------------------------------------------------------
@@ -11,7 +11,7 @@ import struct
11
11
  import subprocess
12
12
  from datetime import datetime, timezone
13
13
  from pathlib import Path
14
- from typing import Optional
14
+ from typing import Dict, Optional
15
15
 
16
16
  from . import api, exitcodes
17
17
  from . import pool as pool_mod
@@ -113,9 +113,11 @@ def valid_before(cert_text: str) -> Optional[datetime]:
113
113
 
114
114
 
115
115
  def ensure_cert(org, cluster_id: int, key: Path, now: datetime, prefer_sso: bool = False,
116
- refresh: bool = False) -> Path:
116
+ refresh: bool = False, justification: Optional[Dict[str, str]] = None) -> Path:
117
117
  """The path of a certificate for ``cluster_id`` with more than 300 s left. Asks the API for a new one otherwise
118
- (or when ``refresh`` is set). A 403 from the API is raised as ``api.ApiError`` for the caller to explain."""
118
+ (or when ``refresh`` is set). A 403 from the API is raised as ``api.ApiError`` for the caller to explain.
119
+ ``justification`` (``reason`` and ``ticket_ref``, only the ones given) goes into the request body: the audit log
120
+ of the customer organization records it for an operator's SUPPORT certificate."""
119
121
  path = cert_path(key, cluster_id)
120
122
  if refresh:
121
123
  path.unlink(missing_ok=True)
@@ -125,7 +127,8 @@ def ensure_cert(org, cluster_id: int, key: Path, now: datetime, prefer_sso: bool
125
127
  return path
126
128
  public_key = Path(f"{key}.pub").read_text().strip()
127
129
  data = api.call("POST", org, "/ssh-certificates", org_scoped=False, ipv4_only=True, prefer_sso=prefer_sso,
128
- scope=pool_mod.ADMIN, body={"cluster_id": cluster_id, "public_key": public_key})
130
+ scope=pool_mod.ADMIN,
131
+ body={"cluster_id": cluster_id, "public_key": public_key, **(justification or {})})
129
132
  certificate = str(data.get("certificate") or "").strip()
130
133
  if not certificate:
131
134
  raise CertError("The API sent no certificate.")
@@ -1408,3 +1408,62 @@ def test_quota_plan_refuses_more_than_ten_regions():
1408
1408
  args = ["cloud-account", "quota-plan", "5"] + [a for i in range(11) for a in ("--region", f"r{i}")]
1409
1409
  r, req = invoke(args, reply(200, {}))
1410
1410
  assert r.exit_code != 0 and not req.called
1411
+
1412
+
1413
+ # --- set-regions ---
1414
+
1415
+ def test_set_regions_puts_the_list_and_prints_pending_and_the_apply_step():
1416
+ body = {"id": 5, "regions": ["us-east-1"], "regions_pending": ["eu-west-1"],
1417
+ "apply": {"terraform": 'module "multicloud" {}\n', "cloudformation": None,
1418
+ "command": "mctl cloud-account apply 5"}}
1419
+ r, req = invoke(["cloud-account", "set-regions", "5", "us-east-1", "eu-west-1"], reply(200, body))
1420
+ assert r.exit_code == 0, r.output
1421
+ method, url = req.call_args.args[:2]
1422
+ assert (method, url) == ("PUT", "https://api.multicloud.io/api/v1/orgs/acme/cloud-accounts/5/regions")
1423
+ assert req.call_args.kwargs["json"] == {"regions": ["us-east-1", "eu-west-1"]}
1424
+ assert "regions: us-east-1" in r.stdout
1425
+ assert "Pending (the role does not allow them yet): eu-west-1" in r.stdout
1426
+ assert 'module "multicloud" {}' in r.stdout
1427
+ assert ("Run: mctl cloud-account apply 5 (it applies the module with the new regions and verifies)"
1428
+ in r.stdout)
1429
+ assert "multicloud.tf" in r.stdout and "Optional" not in r.stdout # a widen: the step is required
1430
+ assert "Apply this Terraform" not in r.stdout and "cloud-account verify" not in r.stdout
1431
+
1432
+
1433
+ def test_set_regions_narrow_prints_the_apply_step_as_optional():
1434
+ body = {"id": 5, "regions": ["us-east-1"], "regions_pending": [],
1435
+ "apply": {"terraform": 'module "multicloud" {}\n', "cloudformation": None,
1436
+ "command": "mctl cloud-account apply 5"}}
1437
+ r, req = invoke(["cloud-account", "set-regions", "5", "us-east-1"], reply(200, body))
1438
+ assert r.exit_code == 0, r.output
1439
+ assert "Run: mctl cloud-account apply 5 (it applies the module with the new regions and verifies)" in r.stdout
1440
+ assert "Optional" in r.stdout and "Pending" not in r.stdout
1441
+
1442
+
1443
+ def test_set_regions_narrow_cloudformation_text_is_optional_too():
1444
+ body = {"id": 5, "regions": ["us-east-1"], "regions_pending": [],
1445
+ "apply": {"terraform": None, "cloudformation": "Update the stack.", "command": None}}
1446
+ r, req = invoke(["cloud-account", "set-regions", "5", "us-east-1"], reply(200, body))
1447
+ assert r.exit_code == 0, r.output
1448
+ assert "Update the stack. Optional: it only tightens the role" in r.stdout
1449
+ assert "cloud-account verify" not in r.stdout
1450
+ body["regions_pending"] = ["eu-west-1"]
1451
+ r, req = invoke(["cloud-account", "set-regions", "5", "us-east-1", "eu-west-1"], reply(200, body))
1452
+ assert "Then run: mctl cloud-account verify 5" in r.stdout and "Optional" not in r.stdout
1453
+
1454
+
1455
+ def test_set_regions_all_sends_null_and_needs_exactly_one_form():
1456
+ r, req = invoke(["cloud-account", "set-regions", "5", "--all"],
1457
+ reply(200, {"id": 5, "regions": None, "regions_pending": []}))
1458
+ assert r.exit_code == 0 and req.call_args.kwargs["json"] == {"regions": None}
1459
+ assert "regions: all" in r.stdout
1460
+ for args in (["cloud-account", "set-regions", "5"], ["cloud-account", "set-regions", "5", "--all", "us-east-1"]):
1461
+ r, req = invoke(args, reply(200, {}))
1462
+ assert r.exit_code == 2 and not req.called
1463
+
1464
+
1465
+ def test_set_regions_exits_non_zero_with_the_api_error():
1466
+ err = {"detail": {"code": "REGIONS_IN_USE", "message": "Pool(s) 7 (web) would have no region left"}}
1467
+ r, _ = invoke(["cloud-account", "set-regions", "5", "us-east-1"], reply(409, err))
1468
+ assert r.exit_code != 0
1469
+ assert "would have no region left" in (r.stdout + r.stderr)
@@ -83,6 +83,15 @@ def test_allow_calls_both_families_and_prints_each_grant(fake):
83
83
  assert "The scheduler applies it within about a minute." in r.stdout
84
84
 
85
85
 
86
+ def test_allow_sends_reason_and_ticket_only_when_given(fake):
87
+ assert invoke("db-access", "allow", "--reason", "Migration", "--ticket", "SUP-5").exit_code == 0
88
+ assert all(c[2]["body"] == {"ttl_seconds": 43200, "reason": "Migration", "ticket_ref": "SUP-5"}
89
+ for c in fake.posts())
90
+ fake.calls.clear()
91
+ assert invoke("db-access", "allow", "--ticket", "SUP-5").exit_code == 0
92
+ assert all(c[2]["body"] == {"ttl_seconds": 43200, "ticket_ref": "SUP-5"} for c in fake.posts())
93
+
94
+
86
95
  def test_allow_warns_about_the_ipv6_prefix(fake):
87
96
  r = invoke("db-access", "allow")
88
97
  assert "/64 covers every device on this network" in r.stdout
@@ -233,6 +233,25 @@ def test_update_sends_only_given_fields(monkeypatch):
233
233
  assert calls[0][2]["json"] == {"max_cost_per_hour": 4.0, "cpu_units_requests": False} # UpdatePoolRequest
234
234
 
235
235
 
236
+ def test_update_cloud_account_is_sent_as_id_objects(monkeypatch):
237
+ r, calls, _ = run(["update", "7", "--cloud-account", "3", "--cloud-account", "9"],
238
+ [reply(200, pool_view())], monkeypatch)
239
+ assert r.exit_code == 0, r.output
240
+ assert calls[0][:2] == ("PATCH", f"{BASE}/pools/7")
241
+ assert calls[0][2]["json"] == {"cloud_accounts": [{"id": 3}, {"id": 9}]}
242
+
243
+
244
+ def test_update_cloud_account_not_with_clouds(monkeypatch):
245
+ r, calls, _ = run(["update", "7", "--cloud-account", "3", "--clouds", '[{"type": "AWS"}]'],
246
+ [reply(200, pool_view())], monkeypatch)
247
+ assert r.exit_code == 2 and not calls
248
+
249
+
250
+ def test_pool_update_help_says_the_list_is_replaced():
251
+ r = CliRunner().invoke(mctl, ["pool", "update", "--help"])
252
+ assert "--cloud-account" in r.output and "Replace" in r.output and "infra" in r.output
253
+
254
+
236
255
  def test_update_set_and_reset_build_settings(monkeypatch):
237
256
  r, calls, _ = run(["update", "7", "--set", "min_vcpus=4", "--set", "grant.cpu=8", "--reset", "idle_reap_minutes",
238
257
  "--max-servers", "5"], [reply(200, pool_view())], monkeypatch)
@@ -651,3 +670,207 @@ def test_cpu_sizing_history(monkeypatch):
651
670
  assert calls[0][2]["params"] == {"window_days": 2}
652
671
  assert "Container app: recommended 230/600u, CLIPPED" in r.stdout
653
672
  assert "2026-11-21T09:00:00Z" in r.stdout
673
+
674
+
675
+ # --- mctl pool cpu-units-mode / cpu-units-select / cpu-units-unselect ---
676
+
677
+ CU = f"{BASE}/pools/412/cpu-sizing"
678
+
679
+
680
+ def cu_preview(direction="up"):
681
+ return {"pool_id": 412, "current": {"mode": "advise", "full_convert_raw": False, "rev": 1},
682
+ "target": {"mode": "full", "full_convert_raw": False}, "direction": direction, "plan_hash": "h1",
683
+ "targets_as_of": "2026-11-23T10:00:00Z", "workloads": [
684
+ {"namespace": "shop", "owner_kind": "Deployment", "owner_name": "web", "choice": "follow",
685
+ "raw": "kept", "containers": [
686
+ {"container": "app", "current_units": None, "current_limit_units": None,
687
+ "current_request_mcpu": 500, "current_limit_mcpu": 1000, "target_units": 230,
688
+ "target_limit_units": 600, "status": "change"}]}],
689
+ "excluded": [{"namespace": "ops", "owner_kind": "Deployment", "owner_name": "cron"}], "released": [],
690
+ "waiting_for_data": 2, "raw_kept": 1, "raw_converted": 0}
691
+
692
+
693
+ def cu_mode(mode="full"):
694
+ return {"pool_id": 412, "mode": mode, "full_convert_raw": False, "rev": 2, "updated_at": "x"}
695
+
696
+
697
+ def test_cpu_units_mode_get(monkeypatch):
698
+ r, calls, _ = run(["cpu-units-mode", "412"], [reply(200, cu_mode("advise"))], monkeypatch)
699
+ assert r.exit_code == 0, r.output
700
+ assert calls[0][:2] == ("GET", CU + "/mode")
701
+ assert "mode advise" in r.stdout
702
+
703
+
704
+ def test_cpu_units_mode_preview_sends_query_and_prints(monkeypatch):
705
+ r, calls, _ = run(["cpu-units-mode", "412", "--preview", "full", "--convert-raw"],
706
+ [reply(200, cu_preview())], monkeypatch)
707
+ assert r.exit_code == 0, r.output
708
+ assert calls[0][:2] == ("GET", CU + "/mode/preview")
709
+ assert calls[0][2]["params"] == {"mode": "full", "full_convert_raw": "true"}
710
+ assert "500/1000m -> 230/600u" in r.stdout and "shop/Deployment/web" in r.stdout
711
+ assert "Excluded: ops/Deployment/cron" in r.stdout and "Waiting for data: 2" in r.stdout
712
+ assert len(calls) == 1
713
+
714
+
715
+ def test_cpu_units_mode_set_yes_sends_the_plan_hash(monkeypatch):
716
+ r, calls, _ = run(["cpu-units-mode", "412", "--set", "full", "--yes"],
717
+ [reply(200, cu_preview()), reply(200, cu_mode())], monkeypatch)
718
+ assert r.exit_code == 0, r.output
719
+ assert [c[0] for c in calls] == ["GET", "PUT"]
720
+ assert calls[1][1] == CU + "/mode"
721
+ assert calls[1][2]["json"] == {"mode": "full", "full_convert_raw": False, "plan_hash": "h1"}
722
+ assert "kubectl rollout restart <kind>/<name> -n <ns>" in r.stdout
723
+
724
+
725
+ def test_cpu_units_mode_set_asks_and_declines(monkeypatch):
726
+ monkeypatch.setattr(cmds, "_stdin_is_tty", lambda: True)
727
+ r, calls, _ = run(["cpu-units-mode", "412", "--set", "full"], [reply(200, cu_preview())], monkeypatch, input="n\n")
728
+ assert r.exit_code != 0 and [c[0] for c in calls] == ["GET"]
729
+ assert "Nothing changed" in r.stderr
730
+
731
+
732
+ def test_cpu_units_mode_set_without_tty_or_yes_refuses(monkeypatch):
733
+ monkeypatch.setattr(cmds, "_stdin_is_tty", lambda: False)
734
+ r, calls, _ = run(["cpu-units-mode", "412", "--set", "full"], [reply(200, cu_preview())], monkeypatch)
735
+ assert r.exit_code != 0 and calls == []
736
+
737
+
738
+ def test_cpu_units_mode_set_409_says_run_again(monkeypatch):
739
+ stale = reply(409, {"detail": {"code": "PLAN_STALE", "message": "stale"}})
740
+ r, _, _ = run(["cpu-units-mode", "412", "--set", "full", "--yes"], [reply(200, cu_preview()), stale], monkeypatch)
741
+ assert r.exit_code != 0 and "plan changed; run again" in r.stderr
742
+
743
+
744
+ def test_cpu_units_mode_preview_and_set_conflict(monkeypatch):
745
+ r, calls, _ = run(["cpu-units-mode", "412", "--preview", "full", "--set", "full"], [reply(200, {})], monkeypatch)
746
+ assert r.exit_code != 0 and calls == []
747
+
748
+
749
+ def test_cpu_units_select_pin(monkeypatch):
750
+ r, calls, _ = run(["cpu-units-select", "412", "shop", "Deployment", "web", "--pin", "app=500:800",
751
+ "--pin", "side=100", "--convert-raw", "--startup-units", "900"],
752
+ [reply(200, {"choice": "pinned"})], monkeypatch)
753
+ assert r.exit_code == 0, r.output
754
+ assert calls[0][:2] == ("PUT", CU + "/workloads/shop/Deployment/web/selection")
755
+ assert calls[0][2]["json"] == {"choice": "pinned", "convert_raw": True, "startup_units": 900, "containers": [
756
+ {"container": "app", "units": 500, "limit_units": 800}, {"container": "side", "units": 100, "limit_units": 100}]}
757
+ assert "rollout restart" in r.stdout
758
+
759
+
760
+ def test_cpu_units_select_default_follow_and_exclude(monkeypatch):
761
+ r, calls, _ = run(["cpu-units-select", "412", "shop", "Deployment", "web"], [reply(200, {"choice": "follow"})],
762
+ monkeypatch)
763
+ assert r.exit_code == 0 and calls[0][2]["json"]["choice"] == "follow" and calls[0][2]["json"]["containers"] is None
764
+ r, calls, _ = run(["cpu-units-select", "412", "shop", "Deployment", "web", "--exclude"],
765
+ [reply(200, {"choice": "excluded"})], monkeypatch)
766
+ assert r.exit_code == 0 and calls[0][2]["json"]["choice"] == "excluded"
767
+
768
+
769
+ def test_cpu_units_select_refuses_pin_with_exclude_and_bad_pin(monkeypatch):
770
+ r, calls, _ = run(["cpu-units-select", "412", "shop", "Deployment", "web", "--pin", "app=5", "--exclude"],
771
+ [reply(200, {})], monkeypatch)
772
+ assert r.exit_code != 0 and calls == []
773
+ r, calls, _ = run(["cpu-units-select", "412", "shop", "Deployment", "web", "--pin", "app"], [reply(200, {})],
774
+ monkeypatch)
775
+ assert r.exit_code != 0 and calls == []
776
+
777
+
778
+ def test_cpu_units_unselect(monkeypatch):
779
+ r, calls, _ = run(["cpu-units-unselect", "412", "shop", "Deployment", "web"], [reply(204, {})], monkeypatch)
780
+ assert r.exit_code == 0, r.output
781
+ assert calls[0][:2] == ("DELETE", CU + "/workloads/shop/Deployment/web/selection")
782
+
783
+
784
+ # --- mctl pool cpu-units-roll / cpu-units-rolls / cpu-units-roll-cancel ---
785
+
786
+ def cu_roll(state="queued", **kw):
787
+ return {"roll_id": 9, "namespace": "shop", "owner_kind": "Deployment", "owner_name": "web", "state": state,
788
+ "reason": None, "allow_downtime": False, "pods_total": None, "pods_rolled": 0, "requested_by": "u",
789
+ "requested_at": "2026-11-24T10:00:00Z", "finished_at": None, "message": None, **kw}
790
+
791
+
792
+ def test_cpu_units_roll_yes_posts_and_prints(monkeypatch):
793
+ r, calls, _ = run(["cpu-units-roll", "412", "shop", "Deployment", "web", "--yes", "--allow-downtime"],
794
+ [reply(202, cu_roll())], monkeypatch)
795
+ assert r.exit_code == 0, r.output
796
+ assert calls[0][:2] == ("POST", CU + "/workloads/shop/Deployment/web/roll")
797
+ assert calls[0][2]["json"] == {"allow_downtime": True}
798
+ assert "Roll 9: shop/Deployment/web: queued" in r.stdout
799
+
800
+
801
+ def test_cpu_units_roll_default_no_downtime_and_json(monkeypatch):
802
+ r, calls, _ = run(["cpu-units-roll", "412", "shop", "Deployment", "web", "-y", "--json"],
803
+ [reply(202, cu_roll())], monkeypatch)
804
+ assert r.exit_code == 0, r.output
805
+ assert calls[0][2]["json"] == {"allow_downtime": False}
806
+ assert json.loads(r.stdout)["roll_id"] == 9
807
+
808
+
809
+ def test_cpu_units_roll_asks_and_declines(monkeypatch):
810
+ monkeypatch.setattr(cmds, "_stdin_is_tty", lambda: True)
811
+ r, calls, _ = run(["cpu-units-roll", "412", "shop", "Deployment", "web"], [reply(202, cu_roll())], monkeypatch,
812
+ input="n\n")
813
+ assert r.exit_code != 0 and calls == [] and "Nothing changed" in r.stderr
814
+
815
+
816
+ def test_cpu_units_roll_asks_and_accepts(monkeypatch):
817
+ monkeypatch.setattr(cmds, "_stdin_is_tty", lambda: True)
818
+ r, calls, _ = run(["cpu-units-roll", "412", "shop", "Deployment", "web"], [reply(202, cu_roll())], monkeypatch,
819
+ input="y\n")
820
+ assert r.exit_code == 0, r.output
821
+ assert [c[0] for c in calls] == ["POST"]
822
+
823
+
824
+ def test_cpu_units_roll_without_tty_or_yes_refuses(monkeypatch):
825
+ monkeypatch.setattr(cmds, "_stdin_is_tty", lambda: False)
826
+ r, calls, _ = run(["cpu-units-roll", "412", "shop", "Deployment", "web"], [reply(202, cu_roll())], monkeypatch)
827
+ assert r.exit_code != 0 and calls == []
828
+
829
+
830
+ def test_cpu_units_roll_409_is_reported(monkeypatch):
831
+ refusal = reply(409, {"detail": {"code": "DOWNTIME_REQUIRED", "message": "1 replica"}})
832
+ r, _, _ = run(["cpu-units-roll", "412", "shop", "Deployment", "web", "--yes"], [refusal], monkeypatch)
833
+ assert r.exit_code != 0 and "1 replica" in r.stderr
834
+
835
+
836
+ def test_cpu_units_rolls_active_and_all(monkeypatch):
837
+ body = {"items": [cu_roll("rolling", pods_total=3, pods_rolled=1),
838
+ cu_roll("blocked_pdb", reason="pdb_timeout", roll_id=8, message="PDB blocks")]}
839
+ r, calls, _ = run(["cpu-units-rolls", "412"], [reply(200, body)], monkeypatch)
840
+ assert r.exit_code == 0, r.output
841
+ assert calls[0][:2] == ("GET", CU + "/rolls") and calls[0][2]["params"] == {"state": "active"}
842
+ assert "shop/Deployment/web" in r.stdout and "1/3" in r.stdout and "pdb_timeout" in r.stdout
843
+ r, calls, _ = run(["cpu-units-rolls", "412", "--all", "--json"], [reply(200, body)], monkeypatch)
844
+ assert calls[0][2]["params"] == {"state": "all"}
845
+ assert len(json.loads(r.stdout)["items"]) == 2
846
+
847
+
848
+ def test_cpu_units_rolls_empty(monkeypatch):
849
+ r, _, _ = run(["cpu-units-rolls", "412"], [reply(200, {"items": []})], monkeypatch)
850
+ assert r.exit_code == 0 and "No active rolls" in r.stdout
851
+
852
+
853
+ def test_cpu_units_roll_cancel(monkeypatch):
854
+ r, calls, _ = run(["cpu-units-roll-cancel", "412", "9"], [reply(202, cu_roll("rolling", pods_total=3))],
855
+ monkeypatch)
856
+ assert r.exit_code == 0, r.output
857
+ assert calls[0][:2] == ("DELETE", CU + "/rolls/9")
858
+ assert "Roll 9: shop/Deployment/web: rolling (0 of 3)" in r.stdout
859
+
860
+
861
+ def test_cpu_units_roll_cancel_terminal_is_200_and_bad_id(monkeypatch):
862
+ r, _, _ = run(["cpu-units-roll-cancel", "412", "9", "--json"], [reply(200, cu_roll("done"))], monkeypatch)
863
+ assert r.exit_code == 0 and json.loads(r.stdout)["state"] == "done"
864
+ r, calls, _ = run(["cpu-units-roll-cancel", "412", "0"], [reply(200, {})], monkeypatch)
865
+ assert r.exit_code != 0 and calls == []
866
+
867
+
868
+ def test_pool_list_prints_kubernetes(monkeypatch):
869
+ """A third pool type (Kubernetes Engine pools, plan Task 2.3) prints as is, in the list and in show."""
870
+ view = pool_view(9, "k8s", type="kubernetes", classes=[], github_org=None)
871
+ r, _, _ = run(["list"], [reply(200, {"pools": [view]})], monkeypatch)
872
+ assert r.exit_code == 0, r.output
873
+ assert "kubernetes" in r.stdout
874
+ r, _, _ = run(["show", "9"], [reply(200, view)], monkeypatch)
875
+ assert r.exit_code == 0, r.output
876
+ assert "kubernetes" in r.stdout
@@ -109,6 +109,19 @@ def test_allow_for_and_cluster_id(fake):
109
109
  assert fake.calls[0][2]["body"] == {"cluster_id": 5, "ttl_seconds": 7200}
110
110
 
111
111
 
112
+ def test_allow_sends_reason_and_ticket_only_when_given(fake):
113
+ r = invoke("ssh", "allow", "--cluster", "5", "--reason", "Disk full", "--ticket", "SUP-9")
114
+ assert r.exit_code == 0, r.stderr
115
+ assert fake.calls[0][2]["body"] == {"cluster_id": 5, "ttl_seconds": 3600, "reason": "Disk full",
116
+ "ticket_ref": "SUP-9"}
117
+ fake.calls.clear()
118
+ assert invoke("ssh", "allow", "--cluster", "5", "--ticket", "SUP-9").exit_code == 0
119
+ assert fake.calls[0][2]["body"] == {"cluster_id": 5, "ttl_seconds": 3600, "ticket_ref": "SUP-9"}
120
+ fake.calls.clear()
121
+ assert invoke("ssh", "allow", "--cluster", "5").exit_code == 0 # a new mctl against an old server
122
+ assert "reason" not in fake.calls[0][2]["body"] and "ticket_ref" not in fake.calls[0][2]["body"]
123
+
124
+
112
125
  def test_allow_cluster_slug_resolves_to_id(fake):
113
126
  r = invoke("ssh", "allow", "--cluster", "platform-a")
114
127
  assert r.exit_code == 0, r.stderr
@@ -195,6 +208,13 @@ def test_revoke(fake):
195
208
  r = invoke("ssh", "revoke", "7")
196
209
  assert r.exit_code == 0, r.stderr
197
210
  assert fake.calls[0][:2] == ("DELETE", "/ssh-access/7") and "7" in r.stdout
211
+ assert "body" not in fake.calls[0][2] # no fields given: nothing new is sent
212
+
213
+
214
+ def test_revoke_sends_reason_and_ticket_as_the_body(fake):
215
+ r = invoke("ssh", "revoke", "7", "--reason", "Done", "--ticket", "SUP-9")
216
+ assert r.exit_code == 0, r.stderr
217
+ assert fake.calls[0][2]["body"] == {"reason": "Done", "ticket_ref": "SUP-9"}
198
218
 
199
219
 
200
220
  def test_revoke_forbidden_is_exit_3(fake, monkeypatch):
@@ -481,6 +501,22 @@ def test_customer_always_posts_grant_even_when_another_members_grant_exists(kama
481
501
  assert probes == ["203.0.113.31"] # and it waited for the port
482
502
 
483
503
 
504
+ def test_operator_connect_sends_reason_and_ticket_to_the_grant_and_the_certificate(kamaji):
505
+ kamaji.state["operator"] = True
506
+ kamaji.grants = [grant(cluster_id=7)]
507
+ assert invoke("ssh", "31", "--yes", "--reason", "Pod crash", "--ticket", "SUP-3").exit_code == 0
508
+ [cert_call] = kamaji.cert_calls()
509
+ assert cert_call[2]["body"]["reason"] == "Pod crash" and cert_call[2]["body"]["ticket_ref"] == "SUP-3"
510
+
511
+
512
+ def test_operator_connect_without_the_flags_sends_neither_field(kamaji):
513
+ kamaji.state["operator"] = True
514
+ kamaji.grants = [grant(cluster_id=7)]
515
+ assert invoke("ssh", "31", "--yes").exit_code == 0
516
+ [cert_call] = kamaji.cert_calls()
517
+ assert set(cert_call[2]["body"]) == {"cluster_id", "public_key"}
518
+
519
+
484
520
  def test_operator_403_names_support_allow_command(kamaji):
485
521
  kamaji.state["operator"] = True
486
522
  kamaji.grants = [grant(cluster_id=7)]
@@ -42,6 +42,15 @@ def issued(monkeypatch):
42
42
  return calls
43
43
 
44
44
 
45
+ @pytest.mark.skipif(not shutil.which("ssh-keygen"), reason="ssh-keygen is not installed")
46
+ def test_ensure_cert_sends_the_justification_only_when_given(tmp_path, issued):
47
+ key = ssh_cert.ensure_key(tmp_path)
48
+ ssh_cert.ensure_cert("acme", 5, key, NOW, refresh=True)
49
+ assert set(issued[-1][3]["body"]) == {"cluster_id", "public_key"}
50
+ ssh_cert.ensure_cert("acme", 5, key, NOW, refresh=True, justification={"reason": "r", "ticket_ref": "T-1"})
51
+ assert issued[-1][3]["body"]["reason"] == "r" and issued[-1][3]["body"]["ticket_ref"] == "T-1"
52
+
53
+
45
54
  @pytest.mark.skipif(not shutil.which("ssh-keygen"), reason="ssh-keygen is not installed")
46
55
  def test_ensure_key_creates_0600_ed25519_once(tmp_path):
47
56
  key = ssh_cert.ensure_key(tmp_path)
@@ -1 +0,0 @@
1
- __version__ = "0.13.1"
File without changes