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/completion.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Shell completion scripts, made from the command line's own definition (so they never go out of date)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
if TYPE_CHECKING:
|
|
9
|
+
from .context import Context
|
|
10
|
+
|
|
11
|
+
Tree = dict[str, tuple[list[str], dict[str, list[str]]]] # command -> (its options, {action: options})
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _subparsers(parser: argparse.ArgumentParser) -> dict[str, argparse.ArgumentParser]:
|
|
15
|
+
for action in parser._actions:
|
|
16
|
+
if isinstance(action, argparse._SubParsersAction):
|
|
17
|
+
return dict(action.choices)
|
|
18
|
+
return {}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _options(parser: argparse.ArgumentParser) -> list[str]:
|
|
22
|
+
return sorted({o for a in parser._actions for o in a.option_strings if o.startswith("--")})
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def tree(root: argparse.ArgumentParser) -> Tree:
|
|
26
|
+
result: Tree = {}
|
|
27
|
+
for name, sub in _subparsers(root).items():
|
|
28
|
+
actions = _subparsers(sub)
|
|
29
|
+
result[name] = (_options(sub), {a: _options(p) for a, p in actions.items()})
|
|
30
|
+
return result
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def bash(root: argparse.ArgumentParser) -> str:
|
|
34
|
+
t = tree(root)
|
|
35
|
+
lines = [
|
|
36
|
+
'# sudoo completion for bash: eval "$(sudoo completion bash)" in ~/.bashrc',
|
|
37
|
+
"_sudoo() {",
|
|
38
|
+
' local cur="${COMP_WORDS[COMP_CWORD]}" cmd="${COMP_WORDS[1]}" sub="${COMP_WORDS[2]}" words=""',
|
|
39
|
+
' if [ "$COMP_CWORD" -eq 1 ]; then',
|
|
40
|
+
f' words="{" ".join(sorted(t))} {" ".join(_options(root))}"',
|
|
41
|
+
" else",
|
|
42
|
+
' case "$cmd" in',
|
|
43
|
+
]
|
|
44
|
+
for name, (options, actions) in sorted(t.items()):
|
|
45
|
+
if actions:
|
|
46
|
+
lines.append(f" {name})")
|
|
47
|
+
lines.append(' if [ "$COMP_CWORD" -eq 2 ]; then words="' + " ".join(sorted(actions)) + '"; else')
|
|
48
|
+
lines.append(' case "$sub" in')
|
|
49
|
+
for action, opts in sorted(actions.items()):
|
|
50
|
+
lines.append(f' {action}) words="{" ".join(opts)}" ;;')
|
|
51
|
+
lines.append(" esac")
|
|
52
|
+
lines.append(" fi ;;")
|
|
53
|
+
else:
|
|
54
|
+
lines.append(f' {name}) words="{" ".join(options)}" ;;')
|
|
55
|
+
lines += [
|
|
56
|
+
" esac",
|
|
57
|
+
" fi",
|
|
58
|
+
' COMPREPLY=($(compgen -W "$words" -- "$cur"))',
|
|
59
|
+
"}",
|
|
60
|
+
"complete -o default -F _sudoo sudoo",
|
|
61
|
+
"",
|
|
62
|
+
]
|
|
63
|
+
return "\n".join(lines)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def zsh(root: argparse.ArgumentParser) -> str:
|
|
67
|
+
return (
|
|
68
|
+
'# sudoo completion for zsh: eval "$(sudoo completion zsh)" in ~/.zshrc\n'
|
|
69
|
+
"autoload -U +X compinit && compinit\n"
|
|
70
|
+
"autoload -U +X bashcompinit && bashcompinit\n" + bash(root).split("\n", 1)[1]
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def fish(root: argparse.ArgumentParser) -> str:
|
|
75
|
+
t = tree(root)
|
|
76
|
+
commands = " ".join(sorted(t))
|
|
77
|
+
lines = [
|
|
78
|
+
"# sudoo completion for fish: sudoo completion fish > ~/.config/fish/completions/sudoo.fish",
|
|
79
|
+
"complete -c sudoo -f",
|
|
80
|
+
f'complete -c sudoo -n "not __fish_seen_subcommand_from {commands}" -a "{commands}"',
|
|
81
|
+
]
|
|
82
|
+
for name, (options, actions) in sorted(t.items()):
|
|
83
|
+
if actions:
|
|
84
|
+
names = " ".join(sorted(actions))
|
|
85
|
+
lines.append(
|
|
86
|
+
f'complete -c sudoo -n "__fish_seen_subcommand_from {name}; and not __fish_seen_subcommand_from {names}" -a "{names}"'
|
|
87
|
+
)
|
|
88
|
+
for action, opts in sorted(actions.items()):
|
|
89
|
+
for opt in opts:
|
|
90
|
+
lines.append(
|
|
91
|
+
f'complete -c sudoo -n "__fish_seen_subcommand_from {name}; and __fish_seen_subcommand_from {action}" -l {opt[2:]}'
|
|
92
|
+
)
|
|
93
|
+
else:
|
|
94
|
+
for opt in options:
|
|
95
|
+
lines.append(f'complete -c sudoo -n "__fish_seen_subcommand_from {name}" -l {opt[2:]}')
|
|
96
|
+
return "\n".join(lines) + "\n"
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def run(ctx: Context, root: argparse.ArgumentParser) -> None:
|
|
100
|
+
script = {"bash": bash, "zsh": zsh, "fish": fish}[ctx.args.shell](root)
|
|
101
|
+
print(script, end="")
|
sudoo_cli/config.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Profiles: which panel to talk to and with which credentials.
|
|
2
|
+
|
|
3
|
+
Where things are kept:
|
|
4
|
+
|
|
5
|
+
* ``config.json`` in the config folder (``$SUDOO_CONFIG_DIR``, else ``$XDG_CONFIG_HOME/sudoo``, else
|
|
6
|
+
``~/.config/sudoo``): the profiles' panel addresses and options, never a secret.
|
|
7
|
+
* The token and the signing secret: in the OS keyring when the optional ``keyring`` package and a working backend
|
|
8
|
+
are present (``pip install 'sudoo-cli[keyring]'``), else in ``credentials.json`` next to it, mode 0600.
|
|
9
|
+
* Environment variables override a profile, and need no file at all (CI): ``SUDOO_URL``, ``SUDOO_TOKEN``,
|
|
10
|
+
``SUDOO_SECRET`` (or ``SUDOO_SIGNING_SECRET``), plus ``SUDOO_PROFILE``, ``SUDOO_CA_CERT``, ``SUDOO_ACTING_FOR``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from .errors import AUTH, USAGE, CliError
|
|
24
|
+
from .signing import ACTING_FOR
|
|
25
|
+
|
|
26
|
+
KEYRING_SERVICE = "sudoo-cli"
|
|
27
|
+
PROFILE_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Profile:
|
|
32
|
+
name: str
|
|
33
|
+
url: str
|
|
34
|
+
token: str
|
|
35
|
+
secret: str
|
|
36
|
+
ca_cert: str | None = None
|
|
37
|
+
acting_for: str | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def config_dir() -> Path:
|
|
41
|
+
if os.environ.get("SUDOO_CONFIG_DIR"):
|
|
42
|
+
return Path(os.environ["SUDOO_CONFIG_DIR"])
|
|
43
|
+
base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
44
|
+
return Path(base) / "sudoo"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _read(path: Path) -> dict[str, Any]:
|
|
48
|
+
try:
|
|
49
|
+
data = json.loads(path.read_text())
|
|
50
|
+
except FileNotFoundError:
|
|
51
|
+
return {}
|
|
52
|
+
except (OSError, ValueError) as error:
|
|
53
|
+
raise CliError(f"Cannot read {path}: {error}") from None
|
|
54
|
+
return data if isinstance(data, dict) else {}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _write_private(path: Path, data: dict[str, Any]) -> None:
|
|
58
|
+
"""Write a file only its owner can read (0600), in a folder only its owner can open (0700), atomically."""
|
|
59
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
60
|
+
with contextlib.suppress(OSError):
|
|
61
|
+
path.parent.chmod(0o700)
|
|
62
|
+
temporary = path.with_name(path.name + ".tmp")
|
|
63
|
+
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
64
|
+
with os.fdopen(fd, "w") as handle:
|
|
65
|
+
json.dump(data, handle, indent=2, sort_keys=True)
|
|
66
|
+
handle.write("\n")
|
|
67
|
+
os.chmod(temporary, 0o600)
|
|
68
|
+
os.replace(temporary, path)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_config() -> dict[str, Any]:
|
|
72
|
+
return _read(config_dir() / "config.json")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def save_config(data: dict[str, Any]) -> None:
|
|
76
|
+
_write_private(config_dir() / "config.json", data)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _keyring() -> Any | None:
|
|
80
|
+
"""The keyring module when it can really store secrets here, else None."""
|
|
81
|
+
if os.environ.get("SUDOO_KEYRING", "").lower() in ("0", "off", "no", "false"):
|
|
82
|
+
return None
|
|
83
|
+
try:
|
|
84
|
+
import keyring
|
|
85
|
+
from keyring.backends import fail
|
|
86
|
+
|
|
87
|
+
backend = keyring.get_keyring()
|
|
88
|
+
if isinstance(backend, fail.Keyring) or getattr(backend, "priority", 1) <= 0:
|
|
89
|
+
return None
|
|
90
|
+
return keyring
|
|
91
|
+
except Exception: # no package, or no usable backend (a server without a desktop session)
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def store_credentials(profile: str, token: str, secret: str) -> str:
|
|
96
|
+
"""Keep the token and signing secret; returns where ("keyring" or the file's path)."""
|
|
97
|
+
keyring = _keyring()
|
|
98
|
+
if keyring is not None:
|
|
99
|
+
try:
|
|
100
|
+
keyring.set_password(KEYRING_SERVICE, f"{profile}:token", token)
|
|
101
|
+
keyring.set_password(KEYRING_SERVICE, f"{profile}:secret", secret)
|
|
102
|
+
_forget_file_credentials(profile)
|
|
103
|
+
return "keyring"
|
|
104
|
+
except Exception: # noqa: S110 the backend refused: fall back to the private file
|
|
105
|
+
pass
|
|
106
|
+
path = config_dir() / "credentials.json"
|
|
107
|
+
data = _read(path)
|
|
108
|
+
data[profile] = {"token": token, "secret": secret}
|
|
109
|
+
_write_private(path, data)
|
|
110
|
+
return str(path)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _forget_file_credentials(profile: str) -> None:
|
|
114
|
+
path = config_dir() / "credentials.json"
|
|
115
|
+
data = _read(path)
|
|
116
|
+
if profile in data:
|
|
117
|
+
del data[profile]
|
|
118
|
+
_write_private(path, data)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def load_credentials(profile: str, where: str | None) -> tuple[str, str]:
|
|
122
|
+
if where == "keyring":
|
|
123
|
+
keyring = _keyring()
|
|
124
|
+
if keyring is not None:
|
|
125
|
+
with contextlib.suppress(Exception):
|
|
126
|
+
token = keyring.get_password(KEYRING_SERVICE, f"{profile}:token") or ""
|
|
127
|
+
secret = keyring.get_password(KEYRING_SERVICE, f"{profile}:secret") or ""
|
|
128
|
+
return token, secret
|
|
129
|
+
return "", ""
|
|
130
|
+
entry = _read(config_dir() / "credentials.json").get(profile) or {}
|
|
131
|
+
return str(entry.get("token") or ""), str(entry.get("secret") or "")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def forget(profile: str) -> bool:
|
|
135
|
+
"""Remove a profile and its credentials; True when it existed."""
|
|
136
|
+
config = load_config()
|
|
137
|
+
profiles = config.get("profiles", {})
|
|
138
|
+
existed = profile in profiles
|
|
139
|
+
if existed:
|
|
140
|
+
del profiles[profile]
|
|
141
|
+
if config.get("default_profile") == profile:
|
|
142
|
+
config.pop("default_profile")
|
|
143
|
+
save_config(config)
|
|
144
|
+
keyring = _keyring()
|
|
145
|
+
if keyring is not None:
|
|
146
|
+
for part in ("token", "secret"):
|
|
147
|
+
with contextlib.suppress(Exception):
|
|
148
|
+
keyring.delete_password(KEYRING_SERVICE, f"{profile}:{part}")
|
|
149
|
+
_forget_file_credentials(profile)
|
|
150
|
+
return existed
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def save_profile(
|
|
154
|
+
name: str, url: str, token: str, secret: str, ca_cert: str | None, acting_for: str | None, make_default: bool
|
|
155
|
+
) -> str:
|
|
156
|
+
if not PROFILE_NAME.fullmatch(name):
|
|
157
|
+
raise CliError("A profile name is 1 to 64 letters, digits, '.', '_' or '-'.", USAGE)
|
|
158
|
+
where = store_credentials(name, token, secret)
|
|
159
|
+
config = load_config()
|
|
160
|
+
profiles = config.setdefault("profiles", {})
|
|
161
|
+
entry: dict[str, Any] = {"url": url, "credentials": "keyring" if where == "keyring" else "file"}
|
|
162
|
+
if ca_cert:
|
|
163
|
+
entry["ca_cert"] = ca_cert
|
|
164
|
+
if acting_for:
|
|
165
|
+
entry["acting_for"] = acting_for
|
|
166
|
+
profiles[name] = entry
|
|
167
|
+
if make_default or "default_profile" not in config:
|
|
168
|
+
config["default_profile"] = name
|
|
169
|
+
save_config(config)
|
|
170
|
+
return where
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def profile_name(requested: str | None) -> str:
|
|
174
|
+
return requested or os.environ.get("SUDOO_PROFILE") or str(load_config().get("default_profile") or "default")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def resolve(requested: str | None, ca_cert: str | None = None, acting_for: str | None = None) -> Profile:
|
|
178
|
+
"""The profile to use, with the environment variables on top of it."""
|
|
179
|
+
env = os.environ
|
|
180
|
+
name = profile_name(requested)
|
|
181
|
+
stored: dict[str, Any] = {}
|
|
182
|
+
token = secret = ""
|
|
183
|
+
# A profile named explicitly is always read; otherwise only when the environment does not give everything.
|
|
184
|
+
env_complete = bool(env.get("SUDOO_URL") and env.get("SUDOO_TOKEN") and _env_secret())
|
|
185
|
+
if requested or not env_complete:
|
|
186
|
+
stored = load_config().get("profiles", {}).get(name) or {}
|
|
187
|
+
if stored:
|
|
188
|
+
token, secret = load_credentials(name, stored.get("credentials"))
|
|
189
|
+
url = env.get("SUDOO_URL") or str(stored.get("url") or "")
|
|
190
|
+
token = env.get("SUDOO_TOKEN") or token
|
|
191
|
+
secret = _env_secret() or secret
|
|
192
|
+
if not (url and token and secret):
|
|
193
|
+
if not stored and not env_complete:
|
|
194
|
+
raise CliError(
|
|
195
|
+
f"Not logged in (profile {name!r}). Run `sudoo login`, or set SUDOO_URL, SUDOO_TOKEN and SUDOO_SECRET.",
|
|
196
|
+
AUTH,
|
|
197
|
+
)
|
|
198
|
+
missing = [label for label, value in (("URL", url), ("token", token), ("signing secret", secret)) if not value]
|
|
199
|
+
raise CliError(f"Profile {name!r} has no {', '.join(missing)}. Run `sudoo login --profile {name}` again.", AUTH)
|
|
200
|
+
acting = acting_for or env.get("SUDOO_ACTING_FOR") or stored.get("acting_for")
|
|
201
|
+
if acting is not None and not ACTING_FOR.fullmatch(acting):
|
|
202
|
+
raise CliError("--acting-for: 1 to 120 letters, digits, '.', '_', '@', '+' or '-'.", USAGE)
|
|
203
|
+
return Profile(
|
|
204
|
+
name=name,
|
|
205
|
+
url=url.rstrip("/"),
|
|
206
|
+
token=token,
|
|
207
|
+
secret=secret,
|
|
208
|
+
ca_cert=ca_cert or env.get("SUDOO_CA_CERT") or stored.get("ca_cert"),
|
|
209
|
+
acting_for=acting,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _env_secret() -> str:
|
|
214
|
+
return os.environ.get("SUDOO_SECRET") or os.environ.get("SUDOO_SIGNING_SECRET") or ""
|
sudoo_cli/context.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""What every command gets: the parsed options, the client (made on first use) and helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from . import config, jobs
|
|
10
|
+
from .client import Client
|
|
11
|
+
from .errors import USAGE, CliError
|
|
12
|
+
from .output import emit_json, info
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Context:
|
|
16
|
+
def __init__(self, args: argparse.Namespace) -> None:
|
|
17
|
+
self.args = args
|
|
18
|
+
self.json: bool = bool(getattr(args, "json", False))
|
|
19
|
+
self.quiet: bool = bool(getattr(args, "quiet", False))
|
|
20
|
+
self._client: Client | None = None
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def client(self) -> Client:
|
|
24
|
+
if self._client is None:
|
|
25
|
+
profile = config.resolve(
|
|
26
|
+
getattr(self.args, "profile", None),
|
|
27
|
+
ca_cert=getattr(self.args, "ca_cert", None),
|
|
28
|
+
acting_for=getattr(self.args, "acting_for", None),
|
|
29
|
+
)
|
|
30
|
+
self._client = Client(
|
|
31
|
+
profile,
|
|
32
|
+
timeout=float(getattr(self.args, "timeout", 60) or 60),
|
|
33
|
+
debug=bool(getattr(self.args, "debug", False)),
|
|
34
|
+
)
|
|
35
|
+
return self._client
|
|
36
|
+
|
|
37
|
+
def confirm(self, question: str, expected: str | None = None) -> None:
|
|
38
|
+
"""Ask before something that cannot be undone; --yes answers for scripts."""
|
|
39
|
+
if getattr(self.args, "yes", False):
|
|
40
|
+
return
|
|
41
|
+
if not sys.stdin.isatty():
|
|
42
|
+
raise CliError(f"{question} Pass --yes to confirm when not running in a terminal.", USAGE)
|
|
43
|
+
prompt = f"{question} Type {expected!r} to confirm: " if expected else f"{question} [y/N] "
|
|
44
|
+
try:
|
|
45
|
+
answer = input(prompt).strip()
|
|
46
|
+
except EOFError:
|
|
47
|
+
answer = ""
|
|
48
|
+
if (expected is not None and answer != expected) or (expected is None and answer.lower() not in ("y", "yes")):
|
|
49
|
+
raise CliError("Not confirmed; nothing was changed.", USAGE)
|
|
50
|
+
|
|
51
|
+
def job(self, started: dict[str, Any]) -> dict[str, Any]:
|
|
52
|
+
"""A job the panel accepted (202): follow it unless --no-wait, print it, fail when it failed."""
|
|
53
|
+
if getattr(self.args, "no_wait", False):
|
|
54
|
+
if self.json:
|
|
55
|
+
emit_json(started)
|
|
56
|
+
else:
|
|
57
|
+
info(f"Started: {started.get('action', 'job')} (job {started.get('id')}). Follow it with:")
|
|
58
|
+
print(f"sudoo jobs follow {started.get('id')}")
|
|
59
|
+
return started
|
|
60
|
+
if not self.quiet and not self.json:
|
|
61
|
+
info(
|
|
62
|
+
f"{started.get('action', 'Job')} on {started.get('instance') or 'the panel'} (job {started.get('id')})"
|
|
63
|
+
)
|
|
64
|
+
final = jobs.follow(
|
|
65
|
+
self.client,
|
|
66
|
+
started,
|
|
67
|
+
quiet=self.quiet,
|
|
68
|
+
live=not getattr(self.args, "poll", False),
|
|
69
|
+
max_wait=getattr(self.args, "wait_timeout", None),
|
|
70
|
+
)
|
|
71
|
+
if self.json:
|
|
72
|
+
emit_json(final)
|
|
73
|
+
jobs.check(final)
|
|
74
|
+
return final
|
sudoo_cli/errors.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Errors the command reports, and the exit code each one ends with (documented in docs/CLI.md)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
# Exit codes. Scripts can rely on them: they never change meaning within a major version.
|
|
8
|
+
OK = 0
|
|
9
|
+
ERROR = 1 # anything not listed below
|
|
10
|
+
USAGE = 2 # a wrong command line, or a refused confirmation
|
|
11
|
+
AUTH = 3 # not logged in, or the panel refused the token or the signature (401)
|
|
12
|
+
FORBIDDEN = 4 # the token's scope or role does not allow this (403)
|
|
13
|
+
NOT_FOUND = 5 # no such instance, project, job, backup... (404)
|
|
14
|
+
CONFLICT = 6 # the panel refused because of the current state (409), for example an instance being created
|
|
15
|
+
INVALID = 7 # the panel refused a value (400, 415, 422)
|
|
16
|
+
RATE_LIMITED = 8 # still 429 after waiting Retry-After the allowed number of times
|
|
17
|
+
SERVER = 9 # the panel failed (5xx)
|
|
18
|
+
NETWORK = 10 # the panel could not be reached: DNS, connection, TLS certificate, timeout
|
|
19
|
+
JOB_FAILED = 11 # a followed job ended with status "failed"
|
|
20
|
+
INTERRUPTED = 130 # Ctrl+C
|
|
21
|
+
|
|
22
|
+
_BY_STATUS = {
|
|
23
|
+
400: INVALID,
|
|
24
|
+
401: AUTH,
|
|
25
|
+
403: FORBIDDEN,
|
|
26
|
+
404: NOT_FOUND,
|
|
27
|
+
405: USAGE,
|
|
28
|
+
409: CONFLICT,
|
|
29
|
+
410: NOT_FOUND,
|
|
30
|
+
415: INVALID,
|
|
31
|
+
422: INVALID,
|
|
32
|
+
429: RATE_LIMITED,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CliError(Exception):
|
|
37
|
+
"""An error with a message for people and an exit code for scripts."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, message: str, code: int = ERROR) -> None:
|
|
40
|
+
super().__init__(message)
|
|
41
|
+
self.message = message
|
|
42
|
+
self.code = code
|
|
43
|
+
|
|
44
|
+
def as_json(self) -> dict[str, Any]:
|
|
45
|
+
return {"error": {"message": self.message, "exit_code": self.code}}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ApiError(CliError):
|
|
49
|
+
"""The panel answered with an error: an RFC 9457 problem detail when it sends one."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, status: int, problem: dict[str, Any], retry_after: float | None = None) -> None:
|
|
52
|
+
self.status = status
|
|
53
|
+
self.problem = problem
|
|
54
|
+
self.retry_after = retry_after
|
|
55
|
+
title = str(problem.get("title") or "Error")
|
|
56
|
+
detail = str(problem.get("detail") or "").strip()
|
|
57
|
+
message = f"{status} {title}" + (f": {detail}" if detail else "")
|
|
58
|
+
if problem.get("request_id"):
|
|
59
|
+
message += f" (request id {problem['request_id']})"
|
|
60
|
+
code = _BY_STATUS.get(status, SERVER if status >= 500 else ERROR)
|
|
61
|
+
super().__init__(message, code)
|
|
62
|
+
|
|
63
|
+
def as_json(self) -> dict[str, Any]:
|
|
64
|
+
result = super().as_json()
|
|
65
|
+
result["error"]["status"] = self.status
|
|
66
|
+
result["error"]["problem"] = self.problem
|
|
67
|
+
return result
|
sudoo_cli/jobs.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Following a job to its end: live through the event stream, or by polling when the stream is not available
|
|
2
|
+
(an `instances` token may not open it, a proxy may cut it)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import http.client
|
|
7
|
+
import sys
|
|
8
|
+
import time
|
|
9
|
+
from typing import IO, Any
|
|
10
|
+
|
|
11
|
+
from .client import Client, parse_events
|
|
12
|
+
from .errors import JOB_FAILED, CliError
|
|
13
|
+
|
|
14
|
+
FINISHED = ("success", "failed")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def finished(job: dict[str, Any]) -> bool:
|
|
18
|
+
return job.get("status") in FINISHED
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Progress:
|
|
22
|
+
"""Prints a line whenever the job's status, step or progress changes, and every new note (to stderr)."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, quiet: bool = False, out: IO[str] | None = None) -> None:
|
|
25
|
+
self.quiet = quiet
|
|
26
|
+
self.out = out or sys.stderr
|
|
27
|
+
self.last: tuple[Any, ...] = ()
|
|
28
|
+
self.notes = 0
|
|
29
|
+
self.started = time.monotonic()
|
|
30
|
+
|
|
31
|
+
def show(self, job: dict[str, Any]) -> None:
|
|
32
|
+
if self.quiet:
|
|
33
|
+
return
|
|
34
|
+
steps = job.get("steps") or []
|
|
35
|
+
current = next((s for s in steps if s.get("status") == "running"), steps[-1] if steps else {})
|
|
36
|
+
state = (job.get("status"), current.get("title"), job.get("progress_percent"))
|
|
37
|
+
if state != self.last:
|
|
38
|
+
self.last = state
|
|
39
|
+
percent = job.get("progress_percent")
|
|
40
|
+
mark = f"{percent:>3}%" if isinstance(percent, int) else " ...".rjust(4)
|
|
41
|
+
title = current.get("title") or job.get("action") or "Job"
|
|
42
|
+
print(f" [{mark}] {title} ({job.get('status')})", file=self.out, flush=True)
|
|
43
|
+
notes = job.get("notes") or []
|
|
44
|
+
for note in notes[self.notes :]:
|
|
45
|
+
print(f" note: {note if isinstance(note, str) else note.get('text', note)}", file=self.out, flush=True)
|
|
46
|
+
self.notes = max(self.notes, len(notes))
|
|
47
|
+
|
|
48
|
+
def done(self, job: dict[str, Any]) -> None:
|
|
49
|
+
if self.quiet:
|
|
50
|
+
return
|
|
51
|
+
took = time.monotonic() - self.started
|
|
52
|
+
if job.get("status") == "success":
|
|
53
|
+
print(f"{job.get('action', 'Job')} finished in {took:.0f} s.", file=self.out)
|
|
54
|
+
else:
|
|
55
|
+
print(f"{job.get('action', 'Job')} failed: {job.get('error') or 'no reason given'}", file=self.out)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def follow(
|
|
59
|
+
client: Client,
|
|
60
|
+
job: dict[str, Any],
|
|
61
|
+
*,
|
|
62
|
+
quiet: bool = False,
|
|
63
|
+
live: bool = True,
|
|
64
|
+
poll_every: float = 2.0,
|
|
65
|
+
max_wait: float | None = None,
|
|
66
|
+
) -> dict[str, Any]:
|
|
67
|
+
"""Wait until the job has finished; returns its last state."""
|
|
68
|
+
progress = Progress(quiet)
|
|
69
|
+
progress.show(job)
|
|
70
|
+
deadline = None if max_wait is None else time.monotonic() + max_wait
|
|
71
|
+
if not finished(job) and live:
|
|
72
|
+
try:
|
|
73
|
+
job = _live(client, job, progress, deadline)
|
|
74
|
+
except (CliError, OSError, http.client.HTTPException) as error:
|
|
75
|
+
client._debug(f"live events unavailable ({error}); polling the job instead")
|
|
76
|
+
while not finished(job):
|
|
77
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
78
|
+
raise CliError(f"The job {job['id']} has not finished yet (still {job.get('status')}).")
|
|
79
|
+
client.sleep(poll_every)
|
|
80
|
+
job = client.get(f"/jobs/{job['id']}").data
|
|
81
|
+
progress.show(job)
|
|
82
|
+
progress.done(job)
|
|
83
|
+
return job
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _live(client: Client, job: dict[str, Any], progress: Progress, deadline: float | None) -> dict[str, Any]:
|
|
87
|
+
job_id = job["id"]
|
|
88
|
+
with client.open_events(["job"]) as stream:
|
|
89
|
+
# Read the job again once the stream is open, so that nothing between the two is missed.
|
|
90
|
+
job = client.get(f"/jobs/{job_id}").data
|
|
91
|
+
progress.show(job)
|
|
92
|
+
if finished(job):
|
|
93
|
+
return job
|
|
94
|
+
for event in parse_events(stream):
|
|
95
|
+
if deadline is not None and time.monotonic() > deadline:
|
|
96
|
+
break
|
|
97
|
+
if event["event"] == "reset":
|
|
98
|
+
job = client.get(f"/jobs/{job_id}").data
|
|
99
|
+
elif event["event"] == "job" and isinstance(event["data"], dict) and event["data"].get("id") == job_id:
|
|
100
|
+
job = event["data"]
|
|
101
|
+
else:
|
|
102
|
+
continue
|
|
103
|
+
progress.show(job)
|
|
104
|
+
if finished(job):
|
|
105
|
+
return job
|
|
106
|
+
return job
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def check(job: dict[str, Any]) -> None:
|
|
110
|
+
"""Raise when a followed job failed (exit code JOB_FAILED)."""
|
|
111
|
+
if job.get("status") == "failed":
|
|
112
|
+
raise CliError(f"{job.get('action', 'Job')} failed: {job.get('error') or 'no reason given'}", JOB_FAILED)
|
sudoo_cli/output.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Output for people (tables, key/value lists) and for scripts (--json)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Callable, Sequence
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
Column = tuple[str, Callable[[dict[str, Any]], Any]]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def emit_json(value: Any) -> None:
|
|
15
|
+
json.dump(value, sys.stdout, indent=2, ensure_ascii=False, sort_keys=False)
|
|
16
|
+
sys.stdout.write("\n")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def text(value: Any) -> str:
|
|
20
|
+
if value is None:
|
|
21
|
+
return "-"
|
|
22
|
+
if isinstance(value, bool):
|
|
23
|
+
return "yes" if value else "no"
|
|
24
|
+
if isinstance(value, (list, tuple)):
|
|
25
|
+
return ", ".join(text(v) for v in value) or "-"
|
|
26
|
+
if isinstance(value, dict):
|
|
27
|
+
return json.dumps(value, ensure_ascii=False)
|
|
28
|
+
return str(value).replace("\n", " ")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def size(value: Any) -> str:
|
|
32
|
+
if not isinstance(value, (int, float)):
|
|
33
|
+
return "-"
|
|
34
|
+
amount = float(value)
|
|
35
|
+
for unit in ("B", "KB", "MB", "GB", "TB"):
|
|
36
|
+
if amount < 1024 or unit == "TB":
|
|
37
|
+
return f"{amount:.0f} {unit}" if unit == "B" else f"{amount:.1f} {unit}"
|
|
38
|
+
amount /= 1024
|
|
39
|
+
return "-"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def when(value: Any) -> str:
|
|
43
|
+
"""An ISO 8601 time or Unix seconds, shown as YYYY-MM-DD HH:MM UTC."""
|
|
44
|
+
if value in (None, ""):
|
|
45
|
+
return "-"
|
|
46
|
+
try:
|
|
47
|
+
if isinstance(value, (int, float)):
|
|
48
|
+
moment = datetime.fromtimestamp(float(value), UTC)
|
|
49
|
+
else:
|
|
50
|
+
moment = datetime.fromisoformat(str(value).replace("Z", "+00:00")).astimezone(UTC)
|
|
51
|
+
except (ValueError, OSError):
|
|
52
|
+
return str(value)
|
|
53
|
+
return moment.strftime("%Y-%m-%d %H:%M")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get(path: str) -> Callable[[dict[str, Any]], Any]:
|
|
57
|
+
"""A column getter for a dotted path: get("odoo.version")."""
|
|
58
|
+
|
|
59
|
+
def read(row: dict[str, Any]) -> Any:
|
|
60
|
+
value: Any = row
|
|
61
|
+
for part in path.split("."):
|
|
62
|
+
value = value.get(part) if isinstance(value, dict) else None
|
|
63
|
+
return value
|
|
64
|
+
|
|
65
|
+
return read
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def table(rows: Sequence[dict[str, Any]], columns: Sequence[Column], empty: str = "Nothing to show.") -> None:
|
|
69
|
+
if not rows:
|
|
70
|
+
print(empty)
|
|
71
|
+
return
|
|
72
|
+
cells = [[text(getter(row)) for _, getter in columns] for row in rows]
|
|
73
|
+
headers = [name for name, _ in columns]
|
|
74
|
+
widths = [max(len(headers[i]), *(len(line[i]) for line in cells)) for i in range(len(headers))]
|
|
75
|
+
print(" ".join(h.upper().ljust(w) for h, w in zip(headers, widths, strict=True)).rstrip())
|
|
76
|
+
for line in cells:
|
|
77
|
+
print(" ".join(c.ljust(w) for c, w in zip(line, widths, strict=True)).rstrip())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def fields(pairs: Sequence[tuple[str, Any]]) -> None:
|
|
81
|
+
width = max((len(k) for k, _ in pairs), default=0)
|
|
82
|
+
for key, value in pairs:
|
|
83
|
+
print(f"{key + ':':<{width + 1}} {text(value)}")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def info(message: str) -> None:
|
|
87
|
+
"""A note for people, on stderr so that stdout stays clean for scripts."""
|
|
88
|
+
print(message, file=sys.stderr)
|