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/__init__.py +3 -0
- sudoo_cli/__main__.py +8 -0
- sudoo_cli/cli.py +336 -0
- sudoo_cli/client.py +320 -0
- sudoo_cli/commands.py +916 -0
- sudoo_cli/completion.py +101 -0
- sudoo_cli/config.py +214 -0
- sudoo_cli/context.py +74 -0
- sudoo_cli/errors.py +67 -0
- sudoo_cli/jobs.py +112 -0
- sudoo_cli/output.py +88 -0
- sudoo_cli/signing.py +65 -0
- sudoo_cli-3.0.0.dist-info/METADATA +116 -0
- sudoo_cli-3.0.0.dist-info/RECORD +17 -0
- sudoo_cli-3.0.0.dist-info/WHEEL +4 -0
- sudoo_cli-3.0.0.dist-info/entry_points.txt +3 -0
- sudoo_cli-3.0.0.dist-info/licenses/LICENSE.md +209 -0
sudoo_cli/__init__.py
ADDED
sudoo_cli/__main__.py
ADDED
sudoo_cli/cli.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""The `sudoo` command line: options, sub-commands and the exit code."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Callable, Sequence
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from . import __version__, commands, completion
|
|
11
|
+
from .context import Context
|
|
12
|
+
from .errors import ERROR, INTERRUPTED, OK, CliError
|
|
13
|
+
from .output import emit_json
|
|
14
|
+
|
|
15
|
+
STAGES = ("development", "staging", "production")
|
|
16
|
+
EDITIONS = ("community", "enterprise")
|
|
17
|
+
STATUSES = ("creating", "online", "starting", "busy", "paused", "switched_off", "stopped", "unknown")
|
|
18
|
+
|
|
19
|
+
EPILOG = """\
|
|
20
|
+
Credentials come from `sudoo login` (a profile) or from SUDOO_URL, SUDOO_TOKEN and SUDOO_SECRET.
|
|
21
|
+
Exit codes: 0 ok, 1 error, 2 usage, 3 not logged in or credentials refused, 4 not allowed, 5 not found,
|
|
22
|
+
6 conflict, 7 invalid value, 8 rate limited, 9 panel error, 10 network or TLS, 11 job failed, 130 interrupted.
|
|
23
|
+
Documentation: https://docs.sudoo.sh/cli"""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _globals(defaults: bool) -> argparse.ArgumentParser:
|
|
27
|
+
"""Options accepted before or after the sub-command (`sudoo --json instances list` = `sudoo instances list --json`)."""
|
|
28
|
+
p = argparse.ArgumentParser(add_help=False)
|
|
29
|
+
d: Any = None if defaults else argparse.SUPPRESS
|
|
30
|
+
g = p.add_argument_group("global options")
|
|
31
|
+
g.add_argument(
|
|
32
|
+
"--profile",
|
|
33
|
+
"-p",
|
|
34
|
+
metavar="NAME",
|
|
35
|
+
default=d,
|
|
36
|
+
help="the profile to use (default: SUDOO_PROFILE or the default profile)",
|
|
37
|
+
)
|
|
38
|
+
g.add_argument("--json", action="store_true", default=False if defaults else d, help="print JSON for scripts")
|
|
39
|
+
g.add_argument("--quiet", "-q", action="store_true", default=False if defaults else d, help="no progress lines")
|
|
40
|
+
g.add_argument(
|
|
41
|
+
"--debug",
|
|
42
|
+
action="store_true",
|
|
43
|
+
default=False if defaults else d,
|
|
44
|
+
help="show requests on stderr (secrets redacted)",
|
|
45
|
+
)
|
|
46
|
+
g.add_argument("--ca-cert", metavar="FILE", default=d, help="trust this CA certificate (PEM) for the panel's TLS")
|
|
47
|
+
g.add_argument("--acting-for", metavar="PERSON", default=d, help="X-Sudoo-Acting-For: who the call is made for")
|
|
48
|
+
g.add_argument(
|
|
49
|
+
"--timeout", type=float, metavar="SECONDS", default=60.0 if defaults else d, help="per request (default 60)"
|
|
50
|
+
)
|
|
51
|
+
return p
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _job_options(p: argparse.ArgumentParser) -> None:
|
|
55
|
+
g = p.add_argument_group("job options")
|
|
56
|
+
g.add_argument("--no-wait", action="store_true", help="return once the panel accepted the job")
|
|
57
|
+
g.add_argument("--poll", action="store_true", help="follow the job by polling instead of the live event stream")
|
|
58
|
+
g.add_argument("--wait-timeout", type=float, metavar="SECONDS", help="give up waiting after this long (exit 1)")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
Handler = Callable[[Context], None]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Builder:
|
|
65
|
+
def __init__(self) -> None:
|
|
66
|
+
self.common = _globals(defaults=False)
|
|
67
|
+
self.root = argparse.ArgumentParser(
|
|
68
|
+
prog="sudoo",
|
|
69
|
+
description="Manage a Sudoo.sh panel: projects, instances, deployments, backups, domains and jobs.",
|
|
70
|
+
epilog=EPILOG,
|
|
71
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
72
|
+
parents=[_globals(defaults=True)],
|
|
73
|
+
)
|
|
74
|
+
self.root.add_argument("--version", action="version", version=f"sudoo-cli {__version__}")
|
|
75
|
+
self.top = self.root.add_subparsers(dest="command", metavar="COMMAND", required=True)
|
|
76
|
+
|
|
77
|
+
def group(self, name: str, help_: str) -> Any:
|
|
78
|
+
p = self.top.add_parser(name, help=help_, description=help_)
|
|
79
|
+
return p.add_subparsers(dest="subcommand", metavar="ACTION", required=True)
|
|
80
|
+
|
|
81
|
+
def cmd(self, parent: Any, name: str, help_: str, handler: Handler, job: bool = False) -> argparse.ArgumentParser:
|
|
82
|
+
p: argparse.ArgumentParser = parent.add_parser(name, help=help_, description=help_, parents=[self.common])
|
|
83
|
+
p.set_defaults(handler=handler)
|
|
84
|
+
if job:
|
|
85
|
+
_job_options(p)
|
|
86
|
+
return p
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
90
|
+
b = Builder()
|
|
91
|
+
top = b.top
|
|
92
|
+
|
|
93
|
+
p = b.cmd(top, "login", "store a panel's address, API token and signing secret in a profile", commands.login)
|
|
94
|
+
p.add_argument("--url", help="the panel's address, https://...")
|
|
95
|
+
p.add_argument("--default", action="store_true", help="make this the default profile")
|
|
96
|
+
p.add_argument("--no-verify", action="store_true", help="do not check the credentials with the panel")
|
|
97
|
+
b.cmd(top, "logout", "forget a profile and its credentials", commands.logout)
|
|
98
|
+
b.cmd(top, "profiles", "list the profiles", commands.profiles)
|
|
99
|
+
b.cmd(top, "status", "the panel's health, version, licence, usage and limits", commands.status)
|
|
100
|
+
b.cmd(top, "version", "the version of this command", commands.version)
|
|
101
|
+
|
|
102
|
+
# projects
|
|
103
|
+
g = b.group("projects", "projects: one GitHub repository each")
|
|
104
|
+
b.cmd(g, "list", "every project", commands.projects_list)
|
|
105
|
+
p = b.cmd(g, "show", "a project and its branches", commands.projects_show)
|
|
106
|
+
p.add_argument("project", help="the project's id")
|
|
107
|
+
p.add_argument("--refresh", action="store_true", help="read the branches from GitHub now")
|
|
108
|
+
p = b.cmd(g, "create", "create a new, empty GitHub repository and its project", commands.projects_create)
|
|
109
|
+
p.add_argument("--owner", required=True, help="the GitHub organisation")
|
|
110
|
+
p.add_argument("--repo-name", required=True, help="the new repository's name")
|
|
111
|
+
p.add_argument("--public", action="store_true", help="a public repository (private by default)")
|
|
112
|
+
p.add_argument("--description")
|
|
113
|
+
_odoo_options(p)
|
|
114
|
+
p.add_argument("--name", help="the project's name (default: the repository's)")
|
|
115
|
+
p = b.cmd(g, "link", "make a project of an existing GitHub repository", commands.projects_link)
|
|
116
|
+
p.add_argument("repository", help="https://github.com/owner/repo")
|
|
117
|
+
_odoo_options(p)
|
|
118
|
+
p.add_argument("--name", help="the project's name (default: the repository's)")
|
|
119
|
+
|
|
120
|
+
# branches
|
|
121
|
+
g = b.group("branches", "a project's branches and their stages")
|
|
122
|
+
p = b.cmd(g, "list", "a project's branches", commands.branches_list)
|
|
123
|
+
p.add_argument("project")
|
|
124
|
+
p.add_argument("--refresh", action="store_true", help="read the branches from GitHub now")
|
|
125
|
+
p = b.cmd(g, "set-stage", "move a branch (and its instances) to a stage", commands.branches_set_stage)
|
|
126
|
+
p.add_argument("project")
|
|
127
|
+
p.add_argument("branch")
|
|
128
|
+
p.add_argument("stage", choices=STAGES)
|
|
129
|
+
p.add_argument("--confirm-production", action="store_true", help="needed to move into or out of production")
|
|
130
|
+
p = b.cmd(
|
|
131
|
+
g,
|
|
132
|
+
"create-instance",
|
|
133
|
+
"an instance of a branch, in the branch's stage",
|
|
134
|
+
commands.branches_create_instance,
|
|
135
|
+
job=True,
|
|
136
|
+
)
|
|
137
|
+
p.add_argument("project")
|
|
138
|
+
p.add_argument("branch")
|
|
139
|
+
p.add_argument("--name")
|
|
140
|
+
p.add_argument("--demo", action=argparse.BooleanOptionalAction, default=None, help="Odoo's demo data (development)")
|
|
141
|
+
p.add_argument("--no-install-modules", action="store_true", help="do not install the repository's modules")
|
|
142
|
+
|
|
143
|
+
# instances
|
|
144
|
+
g = b.group("instances", "instances: list, create, operate, logs")
|
|
145
|
+
p = b.cmd(g, "list", "every instance", commands.instances_list)
|
|
146
|
+
p.add_argument("--project", help="only this project's")
|
|
147
|
+
p.add_argument("--status", choices=STATUSES)
|
|
148
|
+
p.add_argument("--stage", choices=STAGES)
|
|
149
|
+
p = b.cmd(g, "show", "one instance", commands.instances_show)
|
|
150
|
+
p.add_argument("instance")
|
|
151
|
+
p = b.cmd(
|
|
152
|
+
g, "create", "a new instance from a repository's branch, or plain Odoo", commands.instances_create, job=True
|
|
153
|
+
)
|
|
154
|
+
p.add_argument("--repo", help="https://github.com/owner/repo (none: plain Odoo)")
|
|
155
|
+
p.add_argument("--branch")
|
|
156
|
+
_odoo_options(p)
|
|
157
|
+
p.add_argument("--name", help="the instance's name (default: made from the repository and branch)")
|
|
158
|
+
p.add_argument("--stage", choices=STAGES, default="development")
|
|
159
|
+
p.add_argument("--demo", action=argparse.BooleanOptionalAction, default=None, help="Odoo's demo data")
|
|
160
|
+
p.add_argument("--no-install-modules", action="store_true")
|
|
161
|
+
p.add_argument("--delete-after-days", type=int, metavar="DAYS", help="lifetime; 0 keeps it")
|
|
162
|
+
p.add_argument("--from-backup", metavar="FILE", help="start from this backup")
|
|
163
|
+
for name, action, help_ in (
|
|
164
|
+
("start", "start", "start a paused or stopped instance"),
|
|
165
|
+
("pause", "pause", "pause an instance (it starts again on its next visit)"),
|
|
166
|
+
("restart", "restart", "restart Odoo"),
|
|
167
|
+
("stop", "switch-off", "switch an instance off (it stays off until started)"),
|
|
168
|
+
):
|
|
169
|
+
p = b.cmd(g, name, help_, commands.instance_action(action), job=True)
|
|
170
|
+
p.add_argument("instance")
|
|
171
|
+
if name in ("pause", "stop"):
|
|
172
|
+
p.add_argument("--confirm-production", action="store_true", help="needed for a production instance")
|
|
173
|
+
p = b.cmd(g, "delete", "delete an instance, after a backup", commands.instances_delete, job=True)
|
|
174
|
+
p.add_argument("instance")
|
|
175
|
+
p.add_argument("--yes", "-y", action="store_true", help="do not ask")
|
|
176
|
+
p.add_argument("--confirm-production", action="store_true", help="needed for a production instance")
|
|
177
|
+
p.add_argument("--without-backup", action="store_true", help="delete even when the backup fails (audit-logged)")
|
|
178
|
+
p = b.cmd(g, "set", "change an instance's settings or stage", commands.instances_set)
|
|
179
|
+
p.add_argument("instance")
|
|
180
|
+
p.add_argument("--auto-update", action=argparse.BooleanOptionalAction, default=None)
|
|
181
|
+
p.add_argument("--auto-upgrade", action=argparse.BooleanOptionalAction, default=None)
|
|
182
|
+
p.add_argument("--auto-pause", action=argparse.BooleanOptionalAction, default=None)
|
|
183
|
+
p.add_argument("--delete-after-days", type=int, metavar="DAYS", help="0 keeps it")
|
|
184
|
+
p.add_argument("--stage", choices=STAGES)
|
|
185
|
+
p.add_argument("--confirm-production", action="store_true", help="needed to move out of production")
|
|
186
|
+
p = b.cmd(g, "logs", "the end of Odoo's log", commands.instances_logs)
|
|
187
|
+
p.add_argument("instance")
|
|
188
|
+
p.add_argument("--lines", "-n", type=int, default=300, help="1 to 5000 (default 300)")
|
|
189
|
+
p.add_argument("--follow", "-f", action="store_true", help="keep printing new lines")
|
|
190
|
+
p.add_argument("--interval", type=float, default=3.0, help="seconds between reads with --follow")
|
|
191
|
+
p = b.cmd(g, "open", "print an instance's address and open it in a browser", commands.instances_open)
|
|
192
|
+
p.add_argument("instance")
|
|
193
|
+
p.add_argument("--print", dest="print_only", action="store_true", help="only print the address")
|
|
194
|
+
|
|
195
|
+
# deploy
|
|
196
|
+
p = b.cmd(
|
|
197
|
+
top,
|
|
198
|
+
"deploy",
|
|
199
|
+
"get the latest code of a branch into its instances and follow the job",
|
|
200
|
+
commands.deploy,
|
|
201
|
+
job=True,
|
|
202
|
+
)
|
|
203
|
+
p.add_argument("instance", nargs="?", help="the instance to update")
|
|
204
|
+
p.add_argument("--project", help="with --branch: every instance of that branch")
|
|
205
|
+
p.add_argument("--branch")
|
|
206
|
+
p.add_argument("--submodules", action="store_true", help="update the submodules instead")
|
|
207
|
+
|
|
208
|
+
# backups
|
|
209
|
+
g = b.group("backups", "backups on the server and off-site copies")
|
|
210
|
+
p = b.cmd(g, "list", "backups, newest first", commands.backups_list)
|
|
211
|
+
p.add_argument("--instance", help="only this instance's")
|
|
212
|
+
p.add_argument("--offsite", action="store_true", help="the off-site copies instead")
|
|
213
|
+
p = b.cmd(g, "create", "back an instance up now", commands.backups_create, job=True)
|
|
214
|
+
p.add_argument("instance")
|
|
215
|
+
p = b.cmd(
|
|
216
|
+
g,
|
|
217
|
+
"restore",
|
|
218
|
+
"restore a backup into an instance (a before-restore backup is taken first)",
|
|
219
|
+
commands.backups_restore,
|
|
220
|
+
job=True,
|
|
221
|
+
)
|
|
222
|
+
p.add_argument("instance")
|
|
223
|
+
p.add_argument("--file", help="the backup file (default: the instance's latest)")
|
|
224
|
+
p.add_argument("--offsite", metavar="COPY_ID", help="restore this off-site copy instead")
|
|
225
|
+
p.add_argument("--public-key", metavar="PEM_FILE", help="check the off-site copy with this key")
|
|
226
|
+
p.add_argument("--confirm-production", action="store_true", help="needed for a production instance")
|
|
227
|
+
p.add_argument("--yes", "-y", action="store_true", help="do not ask")
|
|
228
|
+
p = b.cmd(g, "download", "download a backup (zip)", commands.backups_download)
|
|
229
|
+
p.add_argument("file")
|
|
230
|
+
p.add_argument("--output", "-o", metavar="PATH", help="file or folder (default: the file's name, here)")
|
|
231
|
+
p.add_argument("--force", action="store_true", help="replace an existing file")
|
|
232
|
+
p = b.cmd(g, "verify", "download and check an off-site copy", commands.backups_verify, job=True)
|
|
233
|
+
p.add_argument("copy", metavar="COPY_ID")
|
|
234
|
+
p.add_argument("--public-key", metavar="PEM_FILE", help="a signing key kept off the server")
|
|
235
|
+
b.cmd(g, "offsite", "the off-site copy settings and state", commands.backups_offsite)
|
|
236
|
+
|
|
237
|
+
# domains
|
|
238
|
+
g = b.group("domains", "an instance's custom domains")
|
|
239
|
+
p = b.cmd(g, "list", "the domains and how to point DNS", commands.domains_list)
|
|
240
|
+
p.add_argument("instance")
|
|
241
|
+
for name, handler, help_ in (
|
|
242
|
+
("add", commands.domains_add, "add a domain"),
|
|
243
|
+
("remove", commands.domains_remove, "remove a domain and its certificate"),
|
|
244
|
+
("status", commands.domains_status, "one domain's state and DNS records"),
|
|
245
|
+
("primary", commands.domains_primary, "make a domain the primary one"),
|
|
246
|
+
):
|
|
247
|
+
p = b.cmd(g, name, help_, handler)
|
|
248
|
+
p.add_argument("instance")
|
|
249
|
+
p.add_argument("domain")
|
|
250
|
+
if name != "status":
|
|
251
|
+
p.add_argument("--confirm-production", action="store_true", help="needed for a production instance")
|
|
252
|
+
if name == "remove":
|
|
253
|
+
p.add_argument("--yes", "-y", action="store_true", help="do not ask")
|
|
254
|
+
if name == "status":
|
|
255
|
+
p.add_argument("--check", action="store_true", help="check DNS (and issue) now")
|
|
256
|
+
|
|
257
|
+
p = b.cmd(top, "shell", "a shell in an instance (the panel's web app only)", commands.shell)
|
|
258
|
+
p.add_argument("instance")
|
|
259
|
+
|
|
260
|
+
g = b.group("mail", "e-mails caught from staging and development instances")
|
|
261
|
+
p = b.cmd(g, "list", "caught e-mails, newest first", commands.mail_list)
|
|
262
|
+
p.add_argument("instance")
|
|
263
|
+
p.add_argument("--search", "-s", help="words in the subject, addresses or text")
|
|
264
|
+
p.add_argument("--limit", type=int, default=50)
|
|
265
|
+
p.add_argument("--offset", type=int, default=0)
|
|
266
|
+
p = b.cmd(g, "show", "one caught e-mail", commands.mail_show)
|
|
267
|
+
p.add_argument("instance")
|
|
268
|
+
p.add_argument("id")
|
|
269
|
+
|
|
270
|
+
g = b.group("resources", "an instance's workers, memory and CPU limits")
|
|
271
|
+
p = b.cmd(g, "show", "what applies, and where it comes from", commands.resources_show)
|
|
272
|
+
p.add_argument("instance")
|
|
273
|
+
p = b.cmd(
|
|
274
|
+
g, "set", "set limits: KEY=VALUE ..., VALUE 'default' follows the stage", commands.resources_set, job=True
|
|
275
|
+
)
|
|
276
|
+
p.add_argument("instance")
|
|
277
|
+
p.add_argument("limits", nargs="+", metavar="KEY=VALUE", help=", ".join(commands.RESOURCE_KEYS))
|
|
278
|
+
p.add_argument("--confirm-production", action="store_true", help="needed for a production instance")
|
|
279
|
+
|
|
280
|
+
g = b.group("jobs", "background jobs")
|
|
281
|
+
p = b.cmd(g, "list", "recent jobs, newest first", commands.jobs_list)
|
|
282
|
+
p.add_argument("--instance")
|
|
283
|
+
p.add_argument("--limit", type=int, default=30)
|
|
284
|
+
p.add_argument("--offset", type=int, default=0)
|
|
285
|
+
p = b.cmd(g, "show", "one job", commands.jobs_show)
|
|
286
|
+
p.add_argument("job")
|
|
287
|
+
p.add_argument("--log", action="store_true", help="add its technical log")
|
|
288
|
+
p = b.cmd(g, "follow", "follow a job until it ends (exit 11 when it failed)", commands.jobs_follow, job=True)
|
|
289
|
+
p.add_argument("job")
|
|
290
|
+
p = b.cmd(g, "log", "a job's technical log", commands.jobs_log)
|
|
291
|
+
p.add_argument("job")
|
|
292
|
+
p.add_argument("--offset", type=int, default=0)
|
|
293
|
+
|
|
294
|
+
g = b.group("users", "the panel's accounts")
|
|
295
|
+
b.cmd(g, "list", "every account (needs a write token)", commands.users_list)
|
|
296
|
+
b.cmd(g, "roles", "the roles and their permissions", commands.roles_list)
|
|
297
|
+
|
|
298
|
+
p = b.cmd(top, "completion", "print a shell completion script", lambda ctx: completion.run(ctx, b.root))
|
|
299
|
+
p.add_argument("shell", choices=("bash", "zsh", "fish"))
|
|
300
|
+
return b.root
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _odoo_options(p: argparse.ArgumentParser) -> None:
|
|
304
|
+
p.add_argument(
|
|
305
|
+
"--odoo-version", "--version", dest="odoo_version", required=True, metavar="VERSION", help="19.0, 18.0, ..."
|
|
306
|
+
)
|
|
307
|
+
p.add_argument("--edition", choices=EDITIONS, default="community")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
311
|
+
parser = build_parser()
|
|
312
|
+
args = parser.parse_args(argv)
|
|
313
|
+
ctx = Context(args)
|
|
314
|
+
try:
|
|
315
|
+
handler: Callable[[Context], None] = args.handler
|
|
316
|
+
handler(ctx)
|
|
317
|
+
return OK
|
|
318
|
+
except CliError as error:
|
|
319
|
+
if ctx.json:
|
|
320
|
+
emit_json(error.as_json())
|
|
321
|
+
print(f"sudoo: {error.message}", file=sys.stderr)
|
|
322
|
+
return error.code
|
|
323
|
+
except KeyboardInterrupt:
|
|
324
|
+
print("", file=sys.stderr)
|
|
325
|
+
return INTERRUPTED
|
|
326
|
+
except BrokenPipeError:
|
|
327
|
+
return OK
|
|
328
|
+
except Exception as error: # an unexpected answer: say what, without a traceback full of internals
|
|
329
|
+
if getattr(args, "debug", False):
|
|
330
|
+
raise
|
|
331
|
+
print(f"sudoo: unexpected error: {type(error).__name__}: {error}. Run again with --debug.", file=sys.stderr)
|
|
332
|
+
return ERROR
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
if __name__ == "__main__":
|
|
336
|
+
sys.exit(main())
|
sudoo_cli/client.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
"""Signed HTTPS calls to a panel's API (/api/v1), with Python's standard library only."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import email.utils
|
|
6
|
+
import http.client
|
|
7
|
+
import ipaddress
|
|
8
|
+
import json
|
|
9
|
+
import secrets
|
|
10
|
+
import socket
|
|
11
|
+
import ssl
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
from collections.abc import Callable, Iterator
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import IO, Any
|
|
20
|
+
|
|
21
|
+
from . import __version__
|
|
22
|
+
from .config import Profile
|
|
23
|
+
from .errors import NETWORK, RATE_LIMITED, USAGE, ApiError, CliError
|
|
24
|
+
from .signing import sign
|
|
25
|
+
|
|
26
|
+
API = "/api/v1"
|
|
27
|
+
MAX_RETRY_WAIT = 300.0 # never sleep longer than this for one Retry-After
|
|
28
|
+
REDACTED = ("authorization", "x-sudoo-signature", "cookie", "set-cookie")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Response:
|
|
33
|
+
status: int
|
|
34
|
+
headers: dict[str, str]
|
|
35
|
+
body: bytes
|
|
36
|
+
_json: Any = field(default=None, repr=False)
|
|
37
|
+
|
|
38
|
+
def json(self) -> Any:
|
|
39
|
+
if self._json is None:
|
|
40
|
+
self._json = json.loads(self.body) if self.body else {}
|
|
41
|
+
return self._json
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def data(self) -> Any:
|
|
45
|
+
payload = self.json()
|
|
46
|
+
return payload.get("data") if isinstance(payload, dict) else payload
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def meta(self) -> dict[str, Any]:
|
|
50
|
+
payload = self.json()
|
|
51
|
+
meta = payload.get("meta") if isinstance(payload, dict) else None
|
|
52
|
+
return meta if isinstance(meta, dict) else {}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _loopback(host: str) -> bool:
|
|
56
|
+
if host == "localhost" or host.endswith(".localhost"):
|
|
57
|
+
return True
|
|
58
|
+
try:
|
|
59
|
+
return ipaddress.ip_address(host).is_loopback
|
|
60
|
+
except ValueError:
|
|
61
|
+
return False
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def check_url(url: str) -> str:
|
|
65
|
+
"""The panel's address: https, or http only on this machine (never send a token in clear over a network)."""
|
|
66
|
+
parsed = urllib.parse.urlsplit(url.strip())
|
|
67
|
+
if parsed.scheme not in ("https", "http") or not parsed.hostname:
|
|
68
|
+
raise CliError(f"Not a panel address: {url!r}. Give it like https://panel.example.com", USAGE)
|
|
69
|
+
if parsed.scheme == "http" and not _loopback(parsed.hostname):
|
|
70
|
+
raise CliError("The panel's address must use https:// (http:// is accepted only for localhost).", USAGE)
|
|
71
|
+
if parsed.query or parsed.fragment:
|
|
72
|
+
raise CliError("Give the panel's address without ?query or #fragment.", USAGE)
|
|
73
|
+
return f"{parsed.scheme}://{parsed.netloc}{parsed.path.rstrip('/')}"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def retry_after_seconds(value: str | None) -> float | None:
|
|
77
|
+
if not value:
|
|
78
|
+
return None
|
|
79
|
+
try:
|
|
80
|
+
return max(0.0, float(value))
|
|
81
|
+
except ValueError:
|
|
82
|
+
moment = email.utils.parsedate_to_datetime(value)
|
|
83
|
+
return max(0.0, moment.timestamp() - time.time()) if moment else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def redact_headers(headers: dict[str, str]) -> dict[str, str]:
|
|
87
|
+
return {k: ("<redacted>" if k.lower() in REDACTED else v) for k, v in headers.items()}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
91
|
+
"""Never follow a redirect: the signature covers the path, and the token must not go to another host."""
|
|
92
|
+
|
|
93
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Client:
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
profile: Profile,
|
|
101
|
+
*,
|
|
102
|
+
timeout: float = 60.0,
|
|
103
|
+
retries: int = 3,
|
|
104
|
+
debug: bool = False,
|
|
105
|
+
log: IO[str] | None = None,
|
|
106
|
+
sleep: Callable[[float], None] | None = None,
|
|
107
|
+
) -> None:
|
|
108
|
+
self.profile = profile
|
|
109
|
+
self.base = check_url(profile.url)
|
|
110
|
+
self.timeout = timeout
|
|
111
|
+
self.retries = retries
|
|
112
|
+
self.debug = debug
|
|
113
|
+
self.log = log or sys.stderr
|
|
114
|
+
self.sleep = sleep or time.sleep
|
|
115
|
+
context: ssl.SSLContext | None = None
|
|
116
|
+
if self.base.startswith("https://"):
|
|
117
|
+
try:
|
|
118
|
+
context = ssl.create_default_context(cafile=profile.ca_cert) if profile.ca_cert else None
|
|
119
|
+
except (OSError, ssl.SSLError) as error:
|
|
120
|
+
raise CliError(f"Cannot use the CA certificate {profile.ca_cert}: {error}", USAGE) from None
|
|
121
|
+
context = context or ssl.create_default_context()
|
|
122
|
+
self._opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context), _NoRedirect)
|
|
123
|
+
|
|
124
|
+
# -- low level -----------------------------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
def _debug(self, text: str) -> None:
|
|
127
|
+
if self.debug:
|
|
128
|
+
print(f"debug: {text}", file=self.log)
|
|
129
|
+
|
|
130
|
+
def _open(
|
|
131
|
+
self,
|
|
132
|
+
method: str,
|
|
133
|
+
path: str,
|
|
134
|
+
body: Any = None,
|
|
135
|
+
*,
|
|
136
|
+
extra: dict[str, str] | None = None,
|
|
137
|
+
timeout: float | None = None,
|
|
138
|
+
) -> http.client.HTTPResponse:
|
|
139
|
+
"""Send one signed request (retrying 429 after Retry-After); returns the open response."""
|
|
140
|
+
data = b"" if body is None else json.dumps(body, separators=(",", ":")).encode()
|
|
141
|
+
attempt = 0
|
|
142
|
+
while True:
|
|
143
|
+
attempt += 1
|
|
144
|
+
headers = sign(self.profile.token, self.profile.secret, method, path, data, self.profile.acting_for)
|
|
145
|
+
headers["User-Agent"] = f"sudoo-cli/{__version__}"
|
|
146
|
+
headers["Accept"] = "application/json"
|
|
147
|
+
headers["X-Request-ID"] = "cli-" + secrets.token_hex(8)
|
|
148
|
+
if body is not None:
|
|
149
|
+
headers["Content-Type"] = "application/json"
|
|
150
|
+
headers.update(extra or {})
|
|
151
|
+
self._debug(f"> {method} {path} {json.dumps(redact_headers(headers))}")
|
|
152
|
+
# check_url allows https, or http on loopback only: never file: or another scheme.
|
|
153
|
+
request = urllib.request.Request( # noqa: S310
|
|
154
|
+
self.base + path, data=data if body is not None else None, method=method
|
|
155
|
+
)
|
|
156
|
+
for key, value in headers.items():
|
|
157
|
+
request.add_header(key, value)
|
|
158
|
+
started = time.monotonic()
|
|
159
|
+
try:
|
|
160
|
+
response: http.client.HTTPResponse = self._opener.open(request, timeout=timeout or self.timeout)
|
|
161
|
+
except urllib.error.HTTPError as error:
|
|
162
|
+
payload = error.read()
|
|
163
|
+
self._debug(
|
|
164
|
+
f"< {error.code} in {time.monotonic() - started:.2f}s, request id {error.headers.get('X-Request-ID')}"
|
|
165
|
+
)
|
|
166
|
+
problem = _problem(payload, error.code, error.reason)
|
|
167
|
+
wait = retry_after_seconds(error.headers.get("Retry-After"))
|
|
168
|
+
if error.code == 429 and attempt <= self.retries:
|
|
169
|
+
wait = 1.0 if wait is None else wait
|
|
170
|
+
if wait <= MAX_RETRY_WAIT:
|
|
171
|
+
print(f"The panel asks to wait {wait:g} s (too many requests); retrying.", file=self.log)
|
|
172
|
+
self.sleep(wait)
|
|
173
|
+
continue
|
|
174
|
+
if 300 <= error.code < 400:
|
|
175
|
+
problem.setdefault(
|
|
176
|
+
"detail", f"The panel redirected to {error.headers.get('Location')}; use that address."
|
|
177
|
+
)
|
|
178
|
+
raise ApiError(error.code, problem, wait) from None
|
|
179
|
+
except urllib.error.URLError as error:
|
|
180
|
+
raise _network_error(self.base, error.reason) from None
|
|
181
|
+
except (TimeoutError, ConnectionError, http.client.HTTPException) as error:
|
|
182
|
+
raise _network_error(self.base, error) from None
|
|
183
|
+
self._debug(
|
|
184
|
+
f"< {response.status} in {time.monotonic() - started:.2f}s, request id {response.headers.get('X-Request-ID')}"
|
|
185
|
+
)
|
|
186
|
+
return response
|
|
187
|
+
|
|
188
|
+
def request(self, method: str, path: str, body: Any = None, query: dict[str, Any] | None = None) -> Response:
|
|
189
|
+
full = API + path + _query(query)
|
|
190
|
+
with self._open(method, full, body) as response:
|
|
191
|
+
try:
|
|
192
|
+
payload = response.read()
|
|
193
|
+
except (TimeoutError, OSError, http.client.HTTPException) as error:
|
|
194
|
+
raise _network_error(self.base, error) from None
|
|
195
|
+
return Response(response.status, dict(response.headers.items()), payload)
|
|
196
|
+
|
|
197
|
+
# -- conveniences --------------------------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
def get(self, path: str, **query: Any) -> Response:
|
|
200
|
+
return self.request("GET", path, query=query)
|
|
201
|
+
|
|
202
|
+
def post(self, path: str, body: Any = None) -> Response:
|
|
203
|
+
return self.request("POST", path, {} if body is None else body)
|
|
204
|
+
|
|
205
|
+
def paged(self, path: str, page: int = 100, **query: Any) -> list[Any]:
|
|
206
|
+
"""Every item of a list that has meta.total (follows limit/offset)."""
|
|
207
|
+
found: list[Any] = []
|
|
208
|
+
while True:
|
|
209
|
+
response = self.get(path, limit=page, offset=len(found), **query)
|
|
210
|
+
items = response.data or []
|
|
211
|
+
found += items
|
|
212
|
+
total = response.meta.get("total")
|
|
213
|
+
if not items or total is None or len(found) >= int(total):
|
|
214
|
+
return found
|
|
215
|
+
|
|
216
|
+
def download(self, path: str, out: IO[bytes], progress: Callable[[int], None] | None = None) -> int:
|
|
217
|
+
size = 0
|
|
218
|
+
with self._open("GET", API + path, timeout=self.timeout) as response:
|
|
219
|
+
while chunk := response.read(1 << 16):
|
|
220
|
+
out.write(chunk)
|
|
221
|
+
size += len(chunk)
|
|
222
|
+
if progress:
|
|
223
|
+
progress(size)
|
|
224
|
+
return size
|
|
225
|
+
|
|
226
|
+
def open_events(
|
|
227
|
+
self, topics: list[str] | None = None, last_event_id: str | None = None, read_timeout: float = 45.0
|
|
228
|
+
) -> http.client.HTTPResponse:
|
|
229
|
+
"""Open the live event stream (Server-Sent Events); read it with `parse_events`.
|
|
230
|
+
|
|
231
|
+
The panel sends a ':' comment every 20 seconds, so a read that waits longer than `read_timeout` means the
|
|
232
|
+
connection is gone (TimeoutError); the caller decides whether to reconnect.
|
|
233
|
+
"""
|
|
234
|
+
path = API + "/events" + _query({"topics": ",".join(topics) if topics else None})
|
|
235
|
+
extra = {"Accept": "text/event-stream"}
|
|
236
|
+
if last_event_id:
|
|
237
|
+
extra["Last-Event-ID"] = last_event_id
|
|
238
|
+
return self._open("GET", path, extra=extra, timeout=read_timeout)
|
|
239
|
+
|
|
240
|
+
def events(self, topics: list[str] | None = None, last_event_id: str | None = None) -> Iterator[dict[str, Any]]:
|
|
241
|
+
with self.open_events(topics, last_event_id) as response:
|
|
242
|
+
yield from parse_events(response)
|
|
243
|
+
|
|
244
|
+
def healthz(self) -> bool:
|
|
245
|
+
"""The panel's public health check (no signature)."""
|
|
246
|
+
request = urllib.request.Request( # noqa: S310 https (http on loopback) only
|
|
247
|
+
self.base + "/healthz", headers={"User-Agent": f"sudoo-cli/{__version__}"}
|
|
248
|
+
)
|
|
249
|
+
try:
|
|
250
|
+
with self._opener.open(request, timeout=min(self.timeout, 15)) as response:
|
|
251
|
+
return 200 <= int(response.status) < 300
|
|
252
|
+
except (urllib.error.URLError, OSError, http.client.HTTPException):
|
|
253
|
+
return False
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def parse_events(lines: Iterator[bytes] | IO[bytes]) -> Iterator[dict[str, Any]]:
|
|
257
|
+
"""Server-Sent Events as {"id", "event", "key", "data"}; the panel sends `data` as {"key", "data"}."""
|
|
258
|
+
event: dict[str, str] = {}
|
|
259
|
+
for raw in lines:
|
|
260
|
+
line = raw.decode("utf-8", "replace").rstrip("\r\n")
|
|
261
|
+
if not line:
|
|
262
|
+
if "data" in event:
|
|
263
|
+
try:
|
|
264
|
+
parsed = json.loads(event["data"])
|
|
265
|
+
except ValueError:
|
|
266
|
+
parsed = {}
|
|
267
|
+
wrapped = isinstance(parsed, dict)
|
|
268
|
+
yield {
|
|
269
|
+
"id": event.get("id"),
|
|
270
|
+
"event": event.get("event", "message"),
|
|
271
|
+
"key": parsed.get("key") if wrapped else None,
|
|
272
|
+
"data": parsed.get("data") if wrapped else parsed,
|
|
273
|
+
}
|
|
274
|
+
event = {}
|
|
275
|
+
elif not line.startswith(":"):
|
|
276
|
+
name, _, value = line.partition(":")
|
|
277
|
+
value = value[1:] if value.startswith(" ") else value
|
|
278
|
+
event[name] = event[name] + "\n" + value if name == "data" and name in event else value
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _query(query: dict[str, Any] | None) -> str:
|
|
282
|
+
items = {k: v for k, v in (query or {}).items() if v is not None and v != ""}
|
|
283
|
+
for key, value in items.items():
|
|
284
|
+
if isinstance(value, bool):
|
|
285
|
+
items[key] = "1" if value else "0"
|
|
286
|
+
return "?" + urllib.parse.urlencode(items) if items else ""
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _problem(payload: bytes, status: int, reason: Any) -> dict[str, Any]:
|
|
290
|
+
try:
|
|
291
|
+
problem = json.loads(payload)
|
|
292
|
+
if isinstance(problem, dict):
|
|
293
|
+
return problem
|
|
294
|
+
except ValueError:
|
|
295
|
+
pass
|
|
296
|
+
text = payload.decode("utf-8", "replace").strip()
|
|
297
|
+
problem = {"title": str(reason or "Error"), "status": status}
|
|
298
|
+
if text and len(text) < 300 and "<" not in text:
|
|
299
|
+
problem["detail"] = text
|
|
300
|
+
return problem
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _network_error(base: str, reason: Any) -> CliError:
|
|
304
|
+
if isinstance(reason, ssl.SSLCertVerificationError):
|
|
305
|
+
return CliError(
|
|
306
|
+
f"The TLS certificate of {base} could not be verified ({reason.verify_message}). "
|
|
307
|
+
"If the panel uses a private certificate authority, pass its certificate with --ca-cert FILE.",
|
|
308
|
+
NETWORK,
|
|
309
|
+
)
|
|
310
|
+
if isinstance(reason, (TimeoutError, socket.timeout)):
|
|
311
|
+
return CliError(f"{base} did not answer in time.", NETWORK)
|
|
312
|
+
return CliError(f"Cannot reach {base}: {reason}", NETWORK)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def quote(part: str, keep_slash: bool = False) -> str:
|
|
316
|
+
"""One part of a path (an instance name, a branch that may contain '/', a file name)."""
|
|
317
|
+
return urllib.parse.quote(part, safe="/" if keep_slash else "")
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
__all__ = ["API", "RATE_LIMITED", "Client", "Response", "check_url", "quote"]
|