sudoo-cli 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sudoo_cli/commands.py ADDED
@@ -0,0 +1,916 @@
1
+ """The commands. Each takes the Context and returns nothing (errors are raised as CliError)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import getpass
6
+ import os
7
+ import platform
8
+ import sys
9
+ import tempfile
10
+ import time
11
+ import webbrowser
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from . import __version__, config
16
+ from .client import Client, check_url, quote
17
+ from .context import Context
18
+ from .errors import CONFLICT, FORBIDDEN, NOT_FOUND, USAGE, ApiError, CliError
19
+ from .output import emit_json, fields, get, info, size, table, text, when
20
+
21
+ # -- account and profiles ---------------------------------------------------------------------------------------------
22
+
23
+
24
+ def login(ctx: Context) -> None:
25
+ a = ctx.args
26
+ name = config.profile_name(a.profile)
27
+ url = a.url or os.environ.get("SUDOO_URL") or _ask("Panel address (https://...): ")
28
+ url = check_url(url)
29
+ token = os.environ.get("SUDOO_TOKEN") or _ask("API token (sudoo_...): ", secret=True)
30
+ secret = (
31
+ os.environ.get("SUDOO_SECRET")
32
+ or os.environ.get("SUDOO_SIGNING_SECRET")
33
+ or _ask("Signing secret: ", secret=True)
34
+ )
35
+ profile = config.Profile(name, url, token.strip(), secret.strip(), a.ca_cert, a.acting_for)
36
+ if not a.no_verify:
37
+ client = Client(profile, timeout=a.timeout, debug=a.debug)
38
+ try:
39
+ client.get("/versions")
40
+ except ApiError as error:
41
+ raise CliError(f"The panel refused these credentials: {error.message}", error.code) from None
42
+ where = config.save_profile(name, url, profile.token, profile.secret, a.ca_cert, a.acting_for, a.default)
43
+ stored = "the OS keyring" if where == "keyring" else f"{where} (mode 0600)"
44
+ if ctx.json:
45
+ emit_json({"profile": name, "url": url, "credentials": "keyring" if where == "keyring" else "file"})
46
+ else:
47
+ print(f"Logged in to {url} as profile {name!r}. Token and signing secret are in {stored}.")
48
+
49
+
50
+ def _ask(prompt: str, secret: bool = False) -> str:
51
+ if not sys.stdin.isatty():
52
+ raise CliError(
53
+ "Not a terminal: give the address with --url and the credentials in SUDOO_TOKEN and SUDOO_SECRET.", USAGE
54
+ )
55
+ value = (getpass.getpass(prompt) if secret else input(prompt)).strip()
56
+ if not value:
57
+ raise CliError("Nothing entered.", USAGE)
58
+ return value
59
+
60
+
61
+ def logout(ctx: Context) -> None:
62
+ name = config.profile_name(ctx.args.profile)
63
+ existed = config.forget(name)
64
+ if ctx.json:
65
+ emit_json({"profile": name, "removed": existed})
66
+ else:
67
+ print(f"Profile {name!r} removed." if existed else f"There was no profile {name!r}.")
68
+
69
+
70
+ def profiles(ctx: Context) -> None:
71
+ data = config.load_config()
72
+ default = data.get("default_profile")
73
+ rows = [
74
+ {"name": n, "url": p.get("url"), "credentials": p.get("credentials"), "default": n == default}
75
+ for n, p in sorted(data.get("profiles", {}).items())
76
+ ]
77
+ if ctx.json:
78
+ emit_json(rows)
79
+ else:
80
+ table(
81
+ rows,
82
+ [
83
+ ("profile", get("name")),
84
+ ("url", get("url")),
85
+ ("credentials", get("credentials")),
86
+ ("default", get("default")),
87
+ ],
88
+ "No profiles. Run `sudoo login`.",
89
+ )
90
+
91
+
92
+ def version(ctx: Context) -> None:
93
+ if ctx.json:
94
+ emit_json({"version": __version__, "python": platform.python_version()})
95
+ else:
96
+ print(f"sudoo-cli {__version__} (Python {platform.python_version()})")
97
+
98
+
99
+ def status(ctx: Context) -> None:
100
+ c = ctx.client
101
+ healthy = c.healthz()
102
+ server = c.get("/server").data
103
+ result: dict[str, Any] = {"url": c.base, "profile": c.profile.name, "healthy": healthy, "server": server}
104
+ for key, path in (("quota", "/instance-quota"), ("capacity", "/server/capacity"), ("licence", "/licence")):
105
+ try:
106
+ result[key] = c.get(path).data
107
+ except ApiError: # a token without the permission, or no measurement yet (503)
108
+ result[key] = None
109
+ if ctx.json:
110
+ emit_json(result)
111
+ return
112
+ metrics = server.get("metrics") or {}
113
+ capacity = result["capacity"] or {}
114
+ quota = result["quota"] or {}
115
+ licence = result["licence"] or {}
116
+ accepted = licence.get("accepted") or {}
117
+ fields(
118
+ [
119
+ ("Panel", f"{c.base} (profile {c.profile.name})"),
120
+ ("Health", "ok" if healthy else "not answering /healthz"),
121
+ ("Version", server.get("version")),
122
+ ("Plugins", server.get("plugins")),
123
+ (
124
+ "Licence",
125
+ f"{accepted.get('version') or licence.get('bundled_version') or '-'}, use {accepted.get('use') or '-'}",
126
+ ),
127
+ (
128
+ "Instances",
129
+ f"{metrics.get('instances_running', '-')} running of {metrics.get('instances_total', quota.get('instances', '-'))}",
130
+ ),
131
+ ("Limit", _limit(quota)),
132
+ ("Capacity", capacity.get("message") or "-"),
133
+ ("CPU", f"{metrics.get('cpu_percent', '-')} %"),
134
+ ("Memory", f"{metrics.get('memory_percent', '-')} %"),
135
+ ("Disk", f"{metrics.get('disk_percent', '-')} %"),
136
+ ]
137
+ )
138
+
139
+
140
+ def _limit(quota: dict[str, Any]) -> str:
141
+ if not quota:
142
+ return "-"
143
+ most = quota.get("max_instances") or "no limit"
144
+ text_ = f"{quota.get('instances', '-')} of {most} instances"
145
+ if quota.get("max_instances_per_user"):
146
+ text_ += f", {quota.get('own_instances')} of {quota['max_instances_per_user']} for this token"
147
+ if quota.get("next_creation_at"):
148
+ text_ += f", next creation at {when(quota['next_creation_at'])}"
149
+ return text_
150
+
151
+
152
+ # -- projects and branches ------------------------------------------------------------------------------------------
153
+
154
+ PROJECT_COLUMNS = [
155
+ ("id", get("id")),
156
+ ("repository", get("repository.full_name")),
157
+ ("odoo", lambda p: f"{get('odoo.version')(p) or '-'} {get('odoo.edition')(p) or ''}".strip()),
158
+ ("branches", get("branches.total")),
159
+ ("instances", get("instances.total")),
160
+ ("attention", get("attention")),
161
+ ]
162
+
163
+
164
+ def projects_list(ctx: Context) -> None:
165
+ response = ctx.client.get("/projects")
166
+ if ctx.json:
167
+ emit_json(response.json())
168
+ else:
169
+ table(response.data or [], PROJECT_COLUMNS, "No projects yet.")
170
+
171
+
172
+ def projects_show(ctx: Context) -> None:
173
+ response = ctx.client.get(f"/projects/{quote(ctx.args.project)}", refresh=ctx.args.refresh or None)
174
+ if ctx.json:
175
+ emit_json(response.json())
176
+ return
177
+ p = response.data
178
+ fields(
179
+ [
180
+ ("Project", p.get("id")),
181
+ ("Name", p.get("name")),
182
+ ("Repository", get("repository.url")(p)),
183
+ ("Odoo", f"{get('odoo.version')(p)} {get('odoo.edition')(p)}"),
184
+ ("Origin", p.get("origin")),
185
+ ("Default branch", response.meta.get("default_branch")),
186
+ ("Created", f"{when(p.get('created_at'))} by {p.get('created_by') or '-'}"),
187
+ ("Instances", get("instances.names")(p)),
188
+ ]
189
+ )
190
+ print()
191
+ _branches_table(p.get("branches_list") or [])
192
+
193
+
194
+ def projects_create(ctx: Context) -> None:
195
+ a = ctx.args
196
+ create: dict[str, Any] = {"owner": a.owner, "name": a.repo_name, "private": not a.public}
197
+ if a.description:
198
+ create["description"] = a.description
199
+ body: dict[str, Any] = {"create": create, "odoo_version": a.odoo_version, "edition": a.edition}
200
+ if a.name:
201
+ body["name"] = a.name
202
+ _project_made(ctx, ctx.client.post("/projects", body))
203
+
204
+
205
+ def projects_link(ctx: Context) -> None:
206
+ a = ctx.args
207
+ body: dict[str, Any] = {"repository": a.repository, "odoo_version": a.odoo_version, "edition": a.edition}
208
+ if a.name:
209
+ body["name"] = a.name
210
+ _project_made(ctx, ctx.client.post("/projects", body))
211
+
212
+
213
+ def _project_made(ctx: Context, response: Any) -> None:
214
+ if ctx.json:
215
+ emit_json(response.json())
216
+ else:
217
+ p = response.data
218
+ print(f"Project {p.get('id')} ({get('repository.full_name')(p)}), origin {p.get('origin')}.")
219
+
220
+
221
+ def _branches_table(branches: list[dict[str, Any]]) -> None:
222
+ table(
223
+ branches,
224
+ [
225
+ ("branch", lambda b: str(b.get("name")) + (" (default)" if b.get("default") else "")),
226
+ ("stage", get("stage")),
227
+ ("commit", get("commit.sha")),
228
+ ("subject", lambda b: (get("commit.subject")(b) or "-")[:50]),
229
+ ("instances", get("instances")),
230
+ ("on github", get("on_github")),
231
+ ],
232
+ "No branches.",
233
+ )
234
+
235
+
236
+ def branches_list(ctx: Context) -> None:
237
+ response = ctx.client.get(f"/projects/{quote(ctx.args.project)}", refresh=ctx.args.refresh or None)
238
+ branches = response.data.get("branches_list") or []
239
+ if ctx.json:
240
+ emit_json({"data": branches, "meta": response.meta})
241
+ else:
242
+ _branches_table(branches)
243
+
244
+
245
+ def branches_set_stage(ctx: Context) -> None:
246
+ a = ctx.args
247
+ body: dict[str, Any] = {"stage": a.stage}
248
+ if a.confirm_production:
249
+ body["confirm_production"] = True
250
+ path = f"/projects/{quote(a.project)}/branches/{quote(a.branch, keep_slash=True)}/stage"
251
+ response = ctx.client.request("PUT", path, body)
252
+ if ctx.json:
253
+ emit_json(response.json())
254
+ else:
255
+ print(f"Branch {a.branch} of {a.project} is now {a.stage}; its instances moved with it.")
256
+
257
+
258
+ def branches_create_instance(ctx: Context) -> None:
259
+ a = ctx.args
260
+ body: dict[str, Any] = {}
261
+ if a.name:
262
+ body["name"] = a.name
263
+ if a.demo is not None:
264
+ body["demo"] = a.demo
265
+ if a.no_install_modules:
266
+ body["install_modules"] = False
267
+ path = f"/projects/{quote(a.project)}/branches/{quote(a.branch, keep_slash=True)}/instances"
268
+ ctx.job(ctx.client.post(path, body).data)
269
+
270
+
271
+ # -- instances --------------------------------------------------------------------------------------------------------
272
+
273
+ INSTANCE_COLUMNS = [
274
+ ("name", get("name")),
275
+ ("status", get("status")),
276
+ ("stage", get("stage")),
277
+ ("project", get("project.id")),
278
+ ("branch", get("git.branch")),
279
+ ("odoo", lambda i: f"{get('odoo.version')(i) or '-'} {(get('odoo.edition')(i) or '')[:3]}".strip()),
280
+ ("url", get("url")),
281
+ ]
282
+
283
+
284
+ def instances_list(ctx: Context) -> None:
285
+ items = ctx.client.paged("/instances")
286
+ a = ctx.args
287
+ if a.project:
288
+ items = [i for i in items if get("project.id")(i) == a.project]
289
+ if a.status:
290
+ items = [i for i in items if i.get("status") == a.status]
291
+ if a.stage:
292
+ items = [i for i in items if i.get("stage") == a.stage]
293
+ if ctx.json:
294
+ emit_json(items)
295
+ else:
296
+ table(items, INSTANCE_COLUMNS, "No instances.")
297
+
298
+
299
+ def _instance(ctx: Context, name: str) -> dict[str, Any]:
300
+ data: dict[str, Any] = ctx.client.get(f"/instances/{quote(name)}").data
301
+ return data
302
+
303
+
304
+ def instances_show(ctx: Context) -> None:
305
+ response = ctx.client.get(f"/instances/{quote(ctx.args.instance)}")
306
+ if ctx.json:
307
+ emit_json(response.json())
308
+ return
309
+ i = response.data
310
+ usage = i.get("usage") or {}
311
+ pairs: list[tuple[str, Any]] = [
312
+ ("Instance", i.get("name")),
313
+ ("Status", i.get("status")),
314
+ ("Stage", i.get("stage")),
315
+ ("URL", i.get("url")),
316
+ ("Project", get("project.id")(i)),
317
+ ("Odoo", f"{get('odoo.version')(i)} {get('odoo.edition')(i)}, database {get('odoo.database')(i)}"),
318
+ ("Repository", get("git.repository")(i)),
319
+ ("Branch", get("git.branch")(i)),
320
+ ("Commit", f"{get('git.commit.sha')(i) or '-'} {get('git.commit.subject')(i) or ''}".strip()),
321
+ ("Settings", i.get("settings")),
322
+ ("CPU", f"{usage.get('cpu_percent', '-')} %"),
323
+ ("Memory", f"{size(usage.get('memory_bytes'))} of {size(usage.get('memory_limit_bytes'))}"),
324
+ ("Disk", size(usage.get("disk_bytes"))),
325
+ ("Created", when(i.get("created_at"))),
326
+ ("Pauses at", when(i.get("pauses_at"))),
327
+ ("Expires at", when(i.get("expires_at"))),
328
+ ]
329
+ if i.get("current_job"):
330
+ job = i["current_job"]
331
+ pairs.append(("Running job", f"{job.get('action')} ({job.get('status')}), sudoo jobs follow {job.get('id')}"))
332
+ if i.get("update_failure"):
333
+ pairs.append(("Last update failed", get("update_failure.message")(i)))
334
+ fields(pairs)
335
+
336
+
337
+ def instances_create(ctx: Context) -> None:
338
+ a = ctx.args
339
+ body: dict[str, Any] = {"version": a.odoo_version, "edition": a.edition, "stage": a.stage}
340
+ for key, value in (
341
+ ("repo", a.repo),
342
+ ("branch", a.branch),
343
+ ("name", a.name),
344
+ ("delete_after_days", a.delete_after_days),
345
+ ("from_backup", a.from_backup),
346
+ ("demo", a.demo),
347
+ ):
348
+ if value is not None:
349
+ body[key] = value
350
+ if a.no_install_modules:
351
+ body["install_modules"] = False
352
+ response = ctx.client.post("/instances", body)
353
+ if not ctx.json and response.headers.get("Content-Location"):
354
+ info(f"New instance: {response.data.get('instance') or response.headers['Content-Location']}")
355
+ ctx.job(response.data)
356
+
357
+
358
+ def instance_action(action: str) -> Any:
359
+ """start, pause, restart, stop (switch-off) and the like: POST /instances/<name>/actions/<action>."""
360
+
361
+ def run(ctx: Context) -> None:
362
+ body: dict[str, Any] = {}
363
+ if getattr(ctx.args, "confirm_production", False):
364
+ body["confirm_production"] = True
365
+ ctx.job(ctx.client.post(f"/instances/{quote(ctx.args.instance)}/actions/{action}", body).data)
366
+
367
+ return run
368
+
369
+
370
+ def instances_delete(ctx: Context) -> None:
371
+ a = ctx.args
372
+ name = a.instance
373
+ ctx.confirm(f"Delete instance {name} (a backup is taken first)?", expected=name)
374
+ body: dict[str, Any] = {"confirm": name}
375
+ if a.confirm_production:
376
+ body["confirm_stage"] = "production"
377
+ if a.without_backup:
378
+ body["without_backup"] = True
379
+ ctx.job(ctx.client.request("DELETE", f"/instances/{quote(name)}", body).data)
380
+
381
+
382
+ def instances_set(ctx: Context) -> None:
383
+ a = ctx.args
384
+ body: dict[str, Any] = {}
385
+ for key in ("auto_update", "auto_upgrade", "auto_pause", "delete_after_days", "stage"):
386
+ value = getattr(a, key)
387
+ if value is not None:
388
+ body[key] = value
389
+ if a.confirm_production:
390
+ body["confirm_production"] = True
391
+ if not body:
392
+ raise CliError("Nothing to change: give at least one option (see sudoo instances set --help).", USAGE)
393
+ response = ctx.client.request("PATCH", f"/instances/{quote(a.instance)}", body)
394
+ if ctx.json:
395
+ emit_json(response.json())
396
+ else:
397
+ print(f"{a.instance}: {', '.join(f'{k} = {text(v)}' for k, v in body.items() if k != 'confirm_production')}")
398
+
399
+
400
+ def instances_logs(ctx: Context) -> None:
401
+ a = ctx.args
402
+ path = f"/instances/{quote(a.instance)}/logs"
403
+ lines = ctx.client.get(path, lines=a.lines).data.get("text", "").splitlines()
404
+ if ctx.json and not a.follow:
405
+ emit_json({"lines": lines})
406
+ return
407
+ for line in lines:
408
+ print(line, flush=True)
409
+ while a.follow:
410
+ ctx.client.sleep(a.interval)
411
+ latest = ctx.client.get(path, lines=max(a.lines, 200)).data.get("text", "").splitlines()
412
+ for line in new_lines(lines, latest):
413
+ print(line, flush=True)
414
+ lines = latest
415
+
416
+
417
+ def new_lines(before: list[str], after: list[str]) -> list[str]:
418
+ """The lines of `after` (a later tail of the same log) that `before` did not show yet."""
419
+ for overlap in range(min(len(before), len(after)), 0, -1):
420
+ if before[-overlap:] == after[:overlap]:
421
+ return after[overlap:]
422
+ return after
423
+
424
+
425
+ def instances_open(ctx: Context) -> None:
426
+ instance = _instance(ctx, ctx.args.instance)
427
+ url = instance.get("url")
428
+ if not url:
429
+ raise CliError(f"{ctx.args.instance} has no address yet (status {instance.get('status')}).", CONFLICT)
430
+ if ctx.json:
431
+ emit_json({"name": instance.get("name"), "url": url})
432
+ return
433
+ print(url)
434
+ if not ctx.args.print_only and sys.stdout.isatty():
435
+ webbrowser.open(url)
436
+
437
+
438
+ def deploy(ctx: Context) -> None:
439
+ """Get the latest code: the `update` action on one instance, or on every instance of a project's branch."""
440
+ a = ctx.args
441
+ if a.instance and (a.project or a.branch):
442
+ raise CliError("Give an instance, or --project and --branch, not both.", USAGE)
443
+ if a.instance:
444
+ names = [a.instance]
445
+ elif a.project and a.branch:
446
+ project = ctx.client.get(f"/projects/{quote(a.project)}", refresh=1).data
447
+ branch = next((b for b in project.get("branches_list") or [] if b.get("name") == a.branch), None)
448
+ if branch is None:
449
+ raise CliError(f"The project {a.project} has no branch {a.branch}.", NOT_FOUND)
450
+ names = _instance_names(branch.get("instances"))
451
+ if not names:
452
+ raise CliError(
453
+ f"Branch {a.branch} has no instance. Create one: sudoo branches create-instance {a.project} {a.branch}",
454
+ NOT_FOUND,
455
+ )
456
+ else:
457
+ raise CliError("Give an instance, or --project and --branch.", USAGE)
458
+ action = "update-submodules" if a.submodules else "update"
459
+ for name in names:
460
+ ctx.job(ctx.client.post(f"/instances/{quote(name)}/actions/{action}", {}).data)
461
+ if not ctx.json and not a.no_wait:
462
+ for name in names:
463
+ print(f"{name}: up to date")
464
+
465
+
466
+ def _instance_names(value: Any) -> list[str]:
467
+ if isinstance(value, list):
468
+ return [v if isinstance(v, str) else str(v.get("name")) for v in value if v]
469
+ if isinstance(value, dict):
470
+ return [str(n) for n in value.get("names") or []]
471
+ if isinstance(value, str):
472
+ return [value]
473
+ return []
474
+
475
+
476
+ # -- backups ----------------------------------------------------------------------------------------------------------
477
+
478
+ BACKUP_COLUMNS = [
479
+ ("file", get("file")),
480
+ ("instance", get("instance")),
481
+ ("kind", get("kind")),
482
+ ("odoo", get("series")),
483
+ ("size", lambda b: size(b.get("size", b.get("size_bytes")))),
484
+ ("created", lambda b: when(b.get("created", b.get("created_at")))),
485
+ ]
486
+ OFFSITE_COLUMNS = [
487
+ ("id", get("id")),
488
+ ("instance", get("instance")),
489
+ ("kind", get("kind")),
490
+ ("status", get("status")),
491
+ ("size", lambda b: size(b.get("size"))),
492
+ ("created", lambda b: when(b.get("created"))),
493
+ ("verified", lambda b: when(b.get("verified_at"))),
494
+ ]
495
+
496
+
497
+ def backups_list(ctx: Context) -> None:
498
+ a = ctx.args
499
+ if a.offsite:
500
+ items = ctx.client.get("/offsite/copies").data or []
501
+ columns = OFFSITE_COLUMNS
502
+ else:
503
+ try:
504
+ items = ctx.client.get("/backups").data or []
505
+ except ApiError as error:
506
+ if error.status != 403 or not a.instance:
507
+ raise
508
+ # Without backups.manage, an instance's own backups are still in GET /instances/<name>.
509
+ items = [dict(b, instance=a.instance) for b in _instance(ctx, a.instance).get("backups") or []]
510
+ columns = BACKUP_COLUMNS
511
+ if a.instance:
512
+ items = [b for b in items if b.get("instance") == a.instance]
513
+ if ctx.json:
514
+ emit_json(items)
515
+ else:
516
+ table(items, columns, "No backups.")
517
+
518
+
519
+ def backups_create(ctx: Context) -> None:
520
+ ctx.job(ctx.client.post(f"/instances/{quote(ctx.args.instance)}/actions/backup", {}).data)
521
+
522
+
523
+ def backups_restore(ctx: Context) -> None:
524
+ a = ctx.args
525
+ if a.file and a.offsite:
526
+ raise CliError("Give --file or --offsite, not both.", USAGE)
527
+ what = a.file or (f"off-site copy {a.offsite}" if a.offsite else "the latest backup")
528
+ ctx.confirm(f"Replace the database and files of {a.instance} with {what}? A before-restore backup is taken first.")
529
+ body: dict[str, Any] = {}
530
+ if a.confirm_production:
531
+ body["confirm_production"] = True
532
+ if a.offsite:
533
+ body["instance"] = a.instance
534
+ if a.public_key:
535
+ body["public_key"] = _read_text(a.public_key)
536
+ response = ctx.client.post(f"/offsite/copies/{quote(a.offsite)}/restore", body)
537
+ else:
538
+ if a.file:
539
+ body["file"] = a.file
540
+ response = ctx.client.post(f"/instances/{quote(a.instance)}/actions/restore", body)
541
+ ctx.job(response.data)
542
+
543
+
544
+ def backups_download(ctx: Context) -> None:
545
+ a = ctx.args
546
+ name = Path(a.file).name
547
+ if name != a.file or name in ("", ".", ".."):
548
+ raise CliError("Give the backup's file name as `sudoo backups list` shows it.", USAGE)
549
+ target = Path(a.output) if a.output else Path(name)
550
+ if target.is_dir():
551
+ target = target / name
552
+ if target.exists() and not a.force:
553
+ raise CliError(f"{target} exists; pass --force to replace it.", USAGE)
554
+ directory = target.parent if str(target.parent) else Path(".")
555
+ fd, temporary = tempfile.mkstemp(prefix=".sudoo-", suffix=".part", dir=directory)
556
+ started = time.monotonic()
557
+ shown = [0.0]
558
+
559
+ def progress(done: int) -> None:
560
+ if not ctx.quiet and sys.stderr.isatty() and time.monotonic() - shown[0] > 0.5:
561
+ shown[0] = time.monotonic()
562
+ print(f"\r {size(done)}", end="", file=sys.stderr, flush=True)
563
+
564
+ try:
565
+ with os.fdopen(fd, "wb") as out:
566
+ total = ctx.client.download(f"/backups/{quote(name)}", out, progress)
567
+ os.replace(temporary, target)
568
+ except BaseException:
569
+ Path(temporary).unlink(missing_ok=True)
570
+ raise
571
+ if ctx.json:
572
+ emit_json({"file": name, "path": str(target), "size": total})
573
+ else:
574
+ if sys.stderr.isatty() and not ctx.quiet:
575
+ print(file=sys.stderr)
576
+ print(f"Saved {target} ({size(total)} in {time.monotonic() - started:.0f} s).")
577
+
578
+
579
+ def backups_verify(ctx: Context) -> None:
580
+ a = ctx.args
581
+ body: dict[str, Any] = {}
582
+ if a.public_key:
583
+ body["public_key"] = _read_text(a.public_key)
584
+ ctx.job(ctx.client.post(f"/offsite/copies/{quote(a.copy)}/verify", body).data)
585
+
586
+
587
+ def backups_offsite(ctx: Context) -> None:
588
+ response = ctx.client.get("/offsite")
589
+ if ctx.json:
590
+ emit_json(response.json())
591
+ return
592
+ o = response.data
593
+ fields(
594
+ [
595
+ ("Off-site copies", "on" if o.get("enabled") else "off"),
596
+ ("Configured", o.get("configured")),
597
+ ("Active", o.get("active")),
598
+ ("Location", o.get("location")),
599
+ ("Stages", o.get("other_stages")),
600
+ ("Kinds", o.get("kinds")),
601
+ ("Key fingerprint", o.get("fingerprint")),
602
+ ("Last scan", o.get("last_scan")),
603
+ ]
604
+ )
605
+
606
+
607
+ def _read_text(path: str) -> str:
608
+ try:
609
+ return Path(path).read_text()
610
+ except OSError as error:
611
+ raise CliError(f"Cannot read {path}: {error}", USAGE) from None
612
+
613
+
614
+ # -- domains ----------------------------------------------------------------------------------------------------------
615
+
616
+
617
+ def domains_list(ctx: Context) -> None:
618
+ response = ctx.client.get(f"/instances/{quote(ctx.args.instance)}/domains")
619
+ if ctx.json:
620
+ emit_json(response.json())
621
+ return
622
+ d = response.data
623
+ target = d.get("target") or {}
624
+ fields(
625
+ [
626
+ ("Custom domains", d.get("mode")),
627
+ ("Default address", d.get("default_url")),
628
+ ("Point DNS to", f"{target.get('record_type')} {target.get('host')}" if target else "-"),
629
+ ("Limit", d.get("limit")),
630
+ ]
631
+ )
632
+ print()
633
+ table(
634
+ d.get("domains") or [],
635
+ [
636
+ ("domain", lambda x: str(x.get("domain")) + (" (primary)" if x.get("primary") else "")),
637
+ ("status", get("status")),
638
+ ("certificate expires", get("certificate.expires_at")),
639
+ ("reason", get("reason")),
640
+ ],
641
+ "No custom domains.",
642
+ )
643
+
644
+
645
+ def _domain_body(ctx: Context, **extra: Any) -> dict[str, Any]:
646
+ body = dict(extra)
647
+ if getattr(ctx.args, "confirm_production", False):
648
+ body["confirm_production"] = True
649
+ return body
650
+
651
+
652
+ def _domain_path(ctx: Context, suffix: str = "") -> str:
653
+ return f"/instances/{quote(ctx.args.instance)}/domains/{quote(ctx.args.domain)}{suffix}"
654
+
655
+
656
+ def _show_domain(ctx: Context, domain: dict[str, Any]) -> None:
657
+ if ctx.json:
658
+ emit_json(domain)
659
+ return
660
+ fields(
661
+ [
662
+ ("Domain", domain.get("domain")),
663
+ ("Status", domain.get("status")),
664
+ ("Reason", domain.get("reason")),
665
+ ("Primary", domain.get("primary")),
666
+ ("URL", domain.get("url")),
667
+ ("Certificate", domain.get("certificate")),
668
+ ("Checked", when(domain.get("checked_at"))),
669
+ ("Next check", when(domain.get("next_check_at"))),
670
+ ]
671
+ )
672
+ records = domain.get("dns_records") or []
673
+ if records:
674
+ print("\nDNS records to create:")
675
+ table(records, [("type", get("type")), ("name", get("name")), ("value", get("value"))])
676
+
677
+
678
+ def domains_add(ctx: Context) -> None:
679
+ body = _domain_body(ctx, domain=ctx.args.domain)
680
+ _show_domain(ctx, ctx.client.post(f"/instances/{quote(ctx.args.instance)}/domains", body).data)
681
+
682
+
683
+ def domains_remove(ctx: Context) -> None:
684
+ ctx.confirm(f"Remove {ctx.args.domain} from {ctx.args.instance} (its certificate is deleted)?")
685
+ ctx.client.request("DELETE", _domain_path(ctx), _domain_body(ctx) or None)
686
+ if ctx.json:
687
+ emit_json({"removed": ctx.args.domain})
688
+ else:
689
+ print(f"{ctx.args.domain} removed.")
690
+
691
+
692
+ def domains_status(ctx: Context) -> None:
693
+ if ctx.args.check:
694
+ domain = ctx.client.post(_domain_path(ctx, "/check")).data
695
+ else:
696
+ data = ctx.client.get(f"/instances/{quote(ctx.args.instance)}/domains").data
697
+ domain = next((d for d in data.get("domains") or [] if d.get("domain") == ctx.args.domain), None)
698
+ if domain is None:
699
+ raise CliError(f"{ctx.args.instance} has no domain {ctx.args.domain}.", NOT_FOUND)
700
+ _show_domain(ctx, domain)
701
+
702
+
703
+ def domains_primary(ctx: Context) -> None:
704
+ _show_domain(ctx, ctx.client.request("PATCH", _domain_path(ctx), _domain_body(ctx, primary=True)).data)
705
+
706
+
707
+ # -- shell, mail, resources -------------------------------------------------------------------------------------------
708
+
709
+
710
+ def shell(ctx: Context) -> None:
711
+ """The panel gives shell tickets to people signed in to it, never to API tokens (docs/PANEL_API.md, 12)."""
712
+ try:
713
+ base = ctx.client.base
714
+ except CliError:
715
+ base = "https://<your panel>"
716
+ raise CliError(
717
+ "The panel opens shells only for people signed in to its web app: API tokens cannot get a shell ticket. "
718
+ f"Open the Shell tab instead: {base}/i/{quote(ctx.args.instance)}/shell",
719
+ FORBIDDEN,
720
+ )
721
+
722
+
723
+ def mail_list(ctx: Context) -> None:
724
+ a = ctx.args
725
+ response = ctx.client.get(f"/instances/{quote(a.instance)}/mail", q=a.search, limit=a.limit, offset=a.offset)
726
+ if ctx.json:
727
+ emit_json(response.json())
728
+ return
729
+ table(
730
+ response.data or [],
731
+ [
732
+ ("id", get("id")),
733
+ ("received", lambda m: when(m.get("received_at"))),
734
+ ("from", get("from")),
735
+ ("to", get("to")),
736
+ ("subject", lambda m: (m.get("subject") or "")[:60]),
737
+ ],
738
+ "No caught e-mail.",
739
+ )
740
+ meta = response.meta
741
+ if meta.get("total") is not None:
742
+ info(f"{meta.get('count', len(response.data or []))} of {meta['total']} e-mails.")
743
+
744
+
745
+ def mail_show(ctx: Context) -> None:
746
+ response = ctx.client.get(f"/instances/{quote(ctx.args.instance)}/mail/{quote(ctx.args.id)}")
747
+ if ctx.json:
748
+ emit_json(response.json())
749
+ return
750
+ m = response.data
751
+ fields(
752
+ [
753
+ ("From", m.get("from")),
754
+ ("To", m.get("to")),
755
+ ("Cc", m.get("cc")),
756
+ ("Subject", m.get("subject")),
757
+ ("Date", m.get("date")),
758
+ ("Attachments", [a.get("filename") for a in m.get("attachment_list") or []]),
759
+ ]
760
+ )
761
+ print()
762
+ print(m.get("text") or "(no text part)")
763
+
764
+
765
+ RESOURCE_KEYS = (
766
+ "odoo_workers",
767
+ "odoo_cron_threads",
768
+ "odoo_limit_memory_soft_mb",
769
+ "odoo_limit_memory_hard_mb",
770
+ "odoo_limit_time_cpu",
771
+ "odoo_limit_time_real",
772
+ "odoo_memory_limit",
773
+ "odoo_cpu_limit",
774
+ "db_memory_limit",
775
+ "db_cpu_limit",
776
+ )
777
+
778
+
779
+ def resources_show(ctx: Context) -> None:
780
+ response = ctx.client.get(f"/instances/{quote(ctx.args.instance)}/resources")
781
+ if ctx.json:
782
+ emit_json(response.json())
783
+ return
784
+ r = response.data
785
+ limits, own, stage = r.get("limits") or {}, r.get("own") or {}, r.get("stage_defaults") or {}
786
+ rows = [
787
+ {"key": k, "value": limits.get(k), "own": own.get(k), "stage": stage.get(k)}
788
+ for k in sorted(set(limits) | set(own) | set(RESOURCE_KEYS))
789
+ ]
790
+ fields([("Stage", r.get("stage")), ("Priority", get("priority.rank")(r)), ("Restart pending", r.get("pending"))])
791
+ print()
792
+ table(
793
+ rows, [("limit", get("key")), ("applies", get("value")), ("own", get("own")), ("stage default", get("stage"))]
794
+ )
795
+ for warning in r.get("warnings") or []:
796
+ info(f"warning: {warning.get('text')}")
797
+
798
+
799
+ def resources_set(ctx: Context) -> None:
800
+ a = ctx.args
801
+ path = f"/instances/{quote(a.instance)}/resources"
802
+ own: dict[str, Any] = dict(ctx.client.get(path).data.get("own") or {})
803
+ for item in a.limits:
804
+ key, sep, value = item.partition("=")
805
+ key = key.strip()
806
+ if not sep or key not in RESOURCE_KEYS:
807
+ raise CliError(f"Give limits as KEY=VALUE, KEY one of: {', '.join(RESOURCE_KEYS)}.", USAGE)
808
+ own[key] = _limit_value(value.strip())
809
+ body: dict[str, Any] = {"limits": own}
810
+ if a.confirm_production:
811
+ body["confirm_production"] = True
812
+ ctx.job(ctx.client.request("PUT", path, body).data)
813
+
814
+
815
+ def _limit_value(value: str) -> Any:
816
+ if value.lower() in ("", "default", "null", "none"):
817
+ return None # follows the stage again
818
+ try:
819
+ return int(value)
820
+ except ValueError:
821
+ try:
822
+ return float(value)
823
+ except ValueError:
824
+ return value # "4g"
825
+
826
+
827
+ # -- jobs and users ---------------------------------------------------------------------------------------------------
828
+
829
+ JOB_COLUMNS = [
830
+ ("id", get("id")),
831
+ ("instance", get("instance")),
832
+ ("action", get("action")),
833
+ ("status", get("status")),
834
+ ("progress", lambda j: f"{j['progress_percent']}%" if isinstance(j.get("progress_percent"), int) else "-"),
835
+ ("by", get("requested_by")),
836
+ ("started", lambda j: when(j.get("started_at"))),
837
+ ]
838
+
839
+
840
+ def jobs_list(ctx: Context) -> None:
841
+ a = ctx.args
842
+ response = ctx.client.get("/jobs", instance=a.instance, limit=a.limit, offset=a.offset)
843
+ if ctx.json:
844
+ emit_json(response.json())
845
+ else:
846
+ table(response.data or [], JOB_COLUMNS, "No jobs.")
847
+
848
+
849
+ def jobs_show(ctx: Context) -> None:
850
+ response = ctx.client.get(f"/jobs/{quote(ctx.args.job)}", include="log" if ctx.args.log else None)
851
+ if ctx.json:
852
+ emit_json(response.json())
853
+ return
854
+ j = response.data
855
+ fields(
856
+ [
857
+ ("Job", j.get("id")),
858
+ ("Instance", j.get("instance")),
859
+ ("Action", j.get("action")),
860
+ ("Status", j.get("status")),
861
+ ("Progress", j.get("progress_percent")),
862
+ ("Requested by", j.get("requested_by")),
863
+ ("Started", when(j.get("started_at"))),
864
+ ("Finished", when(j.get("finished_at"))),
865
+ ("Error", j.get("error")),
866
+ ]
867
+ )
868
+ for step in j.get("steps") or []:
869
+ print(f" {step.get('status', ''):<8} {step.get('title')}")
870
+ for note in j.get("notes") or []:
871
+ print(f" note: {note}")
872
+ if j.get("log"):
873
+ print()
874
+ print(j["log"] if isinstance(j["log"], str) else text(j["log"]))
875
+
876
+
877
+ def jobs_follow(ctx: Context) -> None:
878
+ ctx.job(ctx.client.get(f"/jobs/{quote(ctx.args.job)}").data)
879
+
880
+
881
+ def jobs_log(ctx: Context) -> None:
882
+ response = ctx.client.get(f"/jobs/{quote(ctx.args.job)}/log", offset=ctx.args.offset)
883
+ if ctx.json:
884
+ emit_json(response.json())
885
+ else:
886
+ sys.stdout.write(response.data.get("text", ""))
887
+
888
+
889
+ def users_list(ctx: Context) -> None:
890
+ response = ctx.client.get("/users")
891
+ if ctx.json:
892
+ emit_json(response.json())
893
+ return
894
+ table(
895
+ response.data or [],
896
+ [
897
+ ("user", get("name")),
898
+ ("name", get("display_name")),
899
+ ("email", get("email")),
900
+ ("role", get("role_label")),
901
+ ("second factor", get("second_factors")),
902
+ ("last sign-in", lambda u: when(u.get("last_sign_in_at"))),
903
+ ],
904
+ "No accounts.",
905
+ )
906
+
907
+
908
+ def roles_list(ctx: Context) -> None:
909
+ response = ctx.client.get("/roles")
910
+ if ctx.json:
911
+ emit_json(response.json())
912
+ return
913
+ table(
914
+ response.data.get("roles") or [],
915
+ [("role", get("name")), ("label", get("label")), ("description", get("description"))],
916
+ )