resticbackups3 0.1.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.
@@ -0,0 +1,10 @@
1
+ """restic + S3-compatible storage: init once, then back up from cron."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+ try:
8
+ __version__ = version("resticbackups3")
9
+ except PackageNotFoundError: # running from a source tree without an install
10
+ __version__ = "0.0.0+unknown"
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from resticbackups3.cli import main
4
+
5
+ raise SystemExit(main())
resticbackups3/cli.py ADDED
@@ -0,0 +1,224 @@
1
+ """The `rbs3` / `resticbackups3` command line: argparse tree, sudo re-run, exit codes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ from collections.abc import Sequence
11
+ from pathlib import Path
12
+
13
+ from resticbackups3 import __version__, config, creds, profile, ui
14
+ from resticbackups3.errors import Rbs3Error
15
+ from resticbackups3.ui import Prompter, TerminalPrompter
16
+ from resticbackups3.utils import bullet_list
17
+
18
+ EXIT_OK = 0
19
+ EXIT_FAILED = 1
20
+ EXIT_USAGE = 2
21
+ EXIT_CANCELLED = 130
22
+
23
+ # Commands that read or write root's files, and so run as root.
24
+ NEEDS_ROOT = frozenset({"init"})
25
+
26
+
27
+ def _add_cred_source(p: argparse.ArgumentParser) -> None:
28
+ g = p.add_argument_group(
29
+ "credentials",
30
+ "Give them in an env file, the environment, flags, or at the prompts (nothing given, on a "
31
+ "terminal). These combine: flags > env file > environment, and what is still missing "
32
+ "is asked for.",
33
+ )
34
+ g.add_argument("--env-file", "--envFile", dest="env_file", type=Path, metavar="FILE")
35
+ g.add_argument(
36
+ "--env-var",
37
+ "--envVar",
38
+ dest="env_var",
39
+ action="store_true",
40
+ help="read the keys from this shell's environment",
41
+ )
42
+ for key in creds.KEYS:
43
+ g.add_argument(
44
+ creds.flag_name(key.name),
45
+ dest=key.name,
46
+ metavar="VALUE",
47
+ help="secret: lands in shell history, prefer --env-file or the prompt"
48
+ if key.secret
49
+ else None,
50
+ )
51
+
52
+
53
+ def build_parser() -> argparse.ArgumentParser:
54
+ p = argparse.ArgumentParser(
55
+ prog="rbs3",
56
+ description="restic + S3-compatible storage: init once, then back up from cron.",
57
+ allow_abbrev=False,
58
+ )
59
+ p.add_argument("--version", action="version", version=f"rbs3 {__version__}")
60
+ sub = p.add_subparsers(dest="command", metavar="COMMAND")
61
+
62
+ init = sub.add_parser(
63
+ "init",
64
+ help="create a profile: credentials, settings, checks",
65
+ description="Create a profile: one restic repository, its sources and retention.",
66
+ allow_abbrev=False,
67
+ )
68
+ init.add_argument("profile")
69
+ init.add_argument("--config", type=Path, metavar="FILE", help="settings from this TOML file")
70
+ init.add_argument("--yes", action="store_true", help="do not ask before saving")
71
+ _add_cred_source(init)
72
+ return p
73
+
74
+
75
+ # --- sudo ----------------------------------------------------------------------------------------
76
+
77
+
78
+ def sudo_argv(argv: Sequence[str], preserve: Sequence[str]) -> list[str]:
79
+ cmd = ["sudo"]
80
+ if preserve:
81
+ cmd.append("--preserve-env=" + ",".join(preserve))
82
+ return [*cmd, sys.executable, "-m", "resticbackups3", *argv]
83
+
84
+
85
+ def _elevate(argv: Sequence[str], use_environment: bool) -> None:
86
+ """Run this same command again as root through sudo, then exit with its exit code.
87
+
88
+ The absolute path of this Python is used, so an install in ~/.local works under sudo.
89
+ sudo drops the environment, so with --env-var the known keys are passed on by name, and
90
+ RBS3_ROOT always is: without it the root run would write to the real /etc.
91
+ """
92
+ if os.geteuid() == 0 or os.environ.get("RBS3_NO_SUDO") == "1":
93
+ return
94
+ if shutil.which("sudo") is None:
95
+ raise Rbs3Error("this command needs root, and sudo is not installed; run it as root")
96
+ keys = [k for k in creds.KEY_NAMES if k in os.environ] if use_environment else []
97
+ preserve = [*keys, "RBS3_ROOT"] if os.environ.get("RBS3_ROOT") else keys
98
+ if preserve:
99
+ # A strict sudoers rule may refuse to keep the environment: find out first, so the
100
+ # message can say what to do instead. This also asks for the password once.
101
+ check = subprocess.run(
102
+ ["sudo", "--preserve-env=" + ",".join(preserve), "true"],
103
+ stderr=subprocess.PIPE,
104
+ text=True,
105
+ )
106
+ if check.returncode != 0:
107
+ if "preserve the environment" in check.stderr:
108
+ cannot = []
109
+ if keys:
110
+ cannot.append("--env-var cannot work; use --env-file FILE or the prompts")
111
+ if "RBS3_ROOT" in preserve:
112
+ cannot.append(
113
+ "RBS3_ROOT cannot be passed on; run as root or set RBS3_NO_SUDO=1"
114
+ )
115
+ raise Rbs3Error(
116
+ "sudo is not allowed to keep environment variables here, so "
117
+ + ", and ".join(cannot)
118
+ )
119
+ sys.stderr.write(check.stderr)
120
+ raise SystemExit(EXIT_FAILED)
121
+ cmd = sudo_argv(argv, preserve)
122
+ sys.stdout.flush()
123
+ sys.stderr.flush()
124
+ os.execvp(cmd[0], cmd)
125
+
126
+
127
+ # --- init ----------------------------------------------------------------------------------------
128
+
129
+
130
+ def cmd_init(args: argparse.Namespace, prompter: Prompter) -> int:
131
+ name: str = args.profile
132
+ if profile.exists(name):
133
+ raise Rbs3Error(
134
+ f"profile {name!r} already exists; change it with `rbs3 update-profile {name}` "
135
+ f"(secrets) or `rbs3 update-config {name}` (settings)"
136
+ )
137
+
138
+ flags = {k: getattr(args, k) for k in creds.KEY_NAMES}
139
+ gathered = creds.gather(
140
+ flags=flags, env_file=args.env_file, use_environment=args.env_var, prompter=prompter
141
+ )
142
+ if gathered.secret_flags:
143
+ ui.warn(
144
+ "secrets given as flags (" + ", ".join(gathered.secret_flags) + ") end up in shell "
145
+ "history, in `ps` and in sudo's log (/var/log/auth.log); prefer --env-file or the "
146
+ "prompts"
147
+ )
148
+ if gathered.ignored:
149
+ ui.info("Ignored keys rbs3 does not use: " + ", ".join(gathered.ignored))
150
+ problems = creds.validate(gathered.values)
151
+ if problems:
152
+ raise Rbs3Error(bullet_list("credentials are not valid", problems))
153
+ values = creds.normalize(gathered.values)
154
+
155
+ if args.config is not None:
156
+ cfg = config.load_file(args.config)
157
+ elif prompter.interactive:
158
+ ui.info("Settings for this profile (Enter keeps the default):")
159
+ cfg = config.build_interactive(prompter)
160
+ else:
161
+ raise Rbs3Error("no settings: give --config FILE (no terminal to ask on)")
162
+ for w in config.warnings(cfg):
163
+ ui.warn(w)
164
+
165
+ _print_summary(name, values, cfg)
166
+ if not args.yes and prompter.interactive and not prompter.confirm("Save this profile?", True):
167
+ ui.info("Nothing saved.")
168
+ return EXIT_CANCELLED
169
+
170
+ p = profile.save(
171
+ name,
172
+ profile.render_env(values, creds.KEY_NAMES),
173
+ config.render(cfg, name),
174
+ )
175
+ ui.ok(f"saved {p.env} (0600) and {p.config} (0644)")
176
+ ui.info(
177
+ "rbs3 now keeps its own copy of these settings and secrets, so you may delete the env "
178
+ "and config files you gave it. Keep RESTIC_PASSWORD in a password manager as well: "
179
+ "without it no backup can be restored."
180
+ )
181
+ return EXIT_OK
182
+
183
+
184
+ def _print_summary(name: str, values: dict[str, str], cfg: config.Config) -> None:
185
+ ui.info(f"\nProfile {name}:")
186
+ for key in creds.KEY_NAMES:
187
+ if key in values:
188
+ ui.info(f" {key} = {creds.mask(key, values[key])}")
189
+ if "SMTP_SERVER" not in values:
190
+ ui.info(" email reports: off")
191
+ ui.info(" sources: " + ", ".join(cfg.backup.sources))
192
+ if cfg.backup.exclude:
193
+ ui.info(" exclude: " + ", ".join(cfg.backup.exclude))
194
+ r = cfg.retention
195
+ ui.info(
196
+ f" keep: {r.keep_daily} daily, {r.keep_weekly} weekly, {r.keep_monthly} monthly, "
197
+ f"{r.keep_yearly} yearly"
198
+ )
199
+
200
+
201
+ # --- main ----------------------------------------------------------------------------------------
202
+
203
+
204
+ def main(argv: Sequence[str] | None = None, prompter: Prompter | None = None) -> int:
205
+ argv = list(sys.argv[1:] if argv is None else argv)
206
+ parser = build_parser()
207
+ args = parser.parse_args(argv)
208
+ if args.command is None:
209
+ parser.print_help()
210
+ return EXIT_OK
211
+ if hasattr(args, "profile") and (why := profile.check_name(args.profile)):
212
+ parser.error(why)
213
+ try:
214
+ if args.command in NEEDS_ROOT:
215
+ _elevate(argv, use_environment=getattr(args, "env_var", False))
216
+ if args.command == "init":
217
+ return cmd_init(args, prompter or TerminalPrompter())
218
+ raise AssertionError(args.command)
219
+ except Rbs3Error as e:
220
+ ui.error(str(e))
221
+ return EXIT_FAILED
222
+ except (KeyboardInterrupt, EOFError): # Ctrl+C, or Ctrl+D at a prompt
223
+ ui.error("cancelled")
224
+ return EXIT_CANCELLED