start.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import argparse
  2. import os
  3. import sys
  4. import subprocess
  5. import socket
  6. from pathlib import Path, PurePosixPath
  7. from dataclasses import dataclass
  8. from typing import Any
  9. is_windows = os.name == "nt"
  10. def read_data_sources(file: Path) -> list[Path]:
  11. with open(file) as f:
  12. paths = f.readlines()
  13. return [Path(p_str.strip()).expanduser() for p_str in paths]
  14. @dataclass
  15. class KeePass:
  16. path: Path
  17. bin: str | Path
  18. def read_entry_attribute(self, key, attribute):
  19. return self._exec(["show", "-a", attribute, self.path, key]).strip()
  20. def read_entry_attachment(self, key, attachment):
  21. return self._exec(
  22. ["attachment-export", "--stdout", self.path, key, attachment, "/dev/null"]
  23. )
  24. def _exec(self, args: list[Any]):
  25. try:
  26. return subprocess.check_output([self.bin] + args, text=True)
  27. except subprocess.CalledProcessError as e:
  28. print("\nThere was an error on call to keepass, please check the outout")
  29. exit(1)
  30. @classmethod
  31. def new(cls, path: Path):
  32. binary = (
  33. Path("C:\\") / "Program Files" / "KeePassXC" / "keepassxc-cli.exe"
  34. if is_windows
  35. else "keepassxc-cli"
  36. )
  37. return cls(path=path, bin=binary)
  38. @dataclass
  39. class Secret:
  40. name: str
  41. mode: int
  42. def create(self, keepass: KeePass): ...
  43. @classmethod
  44. def from_line(cls, line: str):
  45. name, type_, *args = line.split(",")
  46. match type_:
  47. case "file":
  48. sub_class = SecretFile
  49. case "keepass-attribute":
  50. sub_class = SecretKeepassAttribute
  51. case "keepass-attachment":
  52. sub_class = SecretKeepassAttachment
  53. return sub_class.from_line(name, *args)
  54. @classmethod
  55. def read_sources(cls, file: Path) -> list["Secret"]:
  56. with open(file) as f:
  57. lines = f.readlines()
  58. return [cls.from_line(l.strip()) for l in lines]
  59. @dataclass
  60. class SecretKeepassAttachment(Secret):
  61. key: str
  62. attachment: str
  63. def create(self, keepass: KeePass):
  64. value = keepass.read_entry_attachment(self.key, self.attachment)
  65. args = ["podman", "secret", "create", "--replace", self.name, "-"]
  66. print(args)
  67. subprocess.run(args, input=value.encode())
  68. @classmethod
  69. def from_line(cls, name: str, key: str, attachment: str):
  70. return cls(name=name, key=key, mode=0o0400, attachment=attachment)
  71. @dataclass
  72. class SecretKeepassAttribute(Secret):
  73. key: str
  74. attribute: str
  75. def create(self, keepass: KeePass):
  76. value = keepass.read_entry_attribute(self.key, self.attribute)
  77. args = ["podman", "secret", "create", "--replace", self.name, "-"]
  78. print(args)
  79. subprocess.run(args, input=value.encode())
  80. @classmethod
  81. def from_line(cls, name: str, key: str, attribute: str):
  82. return cls(name=name, key=key, mode=0o0400, attribute=attribute)
  83. @dataclass
  84. class SecretFile(Secret):
  85. host_path: Path
  86. def create(self, keepass: KeePass):
  87. args = ["podman", "secret", "create", "--replace", self.name, self.host_path]
  88. print(args)
  89. subprocess.run(args)
  90. @classmethod
  91. def from_line(cls, name: str, path: str):
  92. path = Path(path).expanduser()
  93. return cls(host_path=path, name=name, mode=0o0400)
  94. @dataclass
  95. class BorgmaticContainer:
  96. hostname: str
  97. login: str
  98. name: str
  99. image: str = "ghcr.io/borgmatic-collective/borgmatic"
  100. def run(self, data_sources: list[Path], secret_sources: list[Secret]):
  101. container_name = f"borgmatic_{self.login}"
  102. ssh_auth_sock = os.getenv("SSH_AUTH_SOCK")
  103. data_path = Path.cwd() / "pc_backup" / "data"
  104. config_d_path = data_path / "borgmatic.d"
  105. config_path = data_path / "borgmatic"
  106. history_file = data_path / ".bash_history"
  107. history_file.touch()
  108. volumes = [
  109. f"{config_d_path}:/etc/borgmatic.d/",
  110. f"{config_path}:/etc/borgmatic/",
  111. f"{history_file}:/root/.bash_history",
  112. "borg_ssh_dir:/root/.ssh",
  113. "borg_config:/root/.config/borg",
  114. "borg_cache:/root/.cache/borg",
  115. "borgmatic_state:/root/.local/state/borgmatic",
  116. ]
  117. if ssh_auth_sock:
  118. volumes += [f"{ssh_auth_sock}:{ssh_auth_sock}:Z"]
  119. volumes += [f"{vol}:{self.to_source_path(vol)}:ro" for vol in data_sources]
  120. volume_args = [a for vol in volumes for a in ["-v", vol]]
  121. secrets_args = [
  122. a
  123. for s in secret_sources
  124. for a in ["--secret", f"{s.name},mode=0{s.mode:o}"]
  125. ]
  126. args = (
  127. [
  128. "podman",
  129. "run",
  130. "-h",
  131. self.hostname,
  132. "--detach",
  133. "--name",
  134. container_name,
  135. "-e",
  136. "SSH_AUTH_SOCK",
  137. "-e",
  138. "TZ=Europe/Paris",
  139. "-e",
  140. "SSH_KEY_NAME",
  141. "-e",
  142. f"HOST_LOGIN={self.login}",
  143. "--security-opt=label=disable",
  144. ]
  145. + volume_args
  146. + secrets_args
  147. + [self.image]
  148. )
  149. print(args)
  150. subprocess.run(args)
  151. def rm(self):
  152. subprocess.run(["podman", "rm", "-f", self.name])
  153. def exec(self, cmd: list[str], env_vars: list[str] = []):
  154. args = ["podman", "exec", "-ti"]
  155. args += [a for var in env_vars for a in ["-e", var]]
  156. subprocess.run(args + [self.name] + cmd)
  157. @staticmethod
  158. def to_source_path(path: Path):
  159. mount_base = PurePosixPath("/mnt") / "source"
  160. inner_path = PurePosixPath(path)
  161. with_drive = PurePosixPath(inner_path.parts[0].replace(":", "")).joinpath(
  162. *inner_path.parts[1:]
  163. )
  164. return mount_base / with_drive.relative_to(with_drive.anchor)
  165. @classmethod
  166. def new(cls, hostname: str, login: str):
  167. return cls(hostname, login, f"borgmatic_{login}")
  168. class CliArguments:
  169. @staticmethod
  170. def read_command(parser):
  171. args = parser.parse_args()
  172. return args.command(args)
  173. @staticmethod
  174. def new() -> argparse.ArgumentParser:
  175. parser = argparse.ArgumentParser(prog=sys.argv[0])
  176. subparsers = parser.add_subparsers()
  177. for sub in [
  178. CommandStart,
  179. CommandRm,
  180. CommandBash,
  181. CommandCreateRepo,
  182. CommandExportKey,
  183. CommandCreateSecrets,
  184. ]:
  185. p = subparsers.add_parser(sub.command, help=sub.help)
  186. sub.init_subparser(p)
  187. p.set_defaults(command=sub)
  188. return parser
  189. class Command:
  190. def __init__(self, namespace) -> None:
  191. for k, v in vars(namespace).items():
  192. if k != "type_":
  193. setattr(self, k, v)
  194. @classmethod
  195. def init_subparser(cls, p): ...
  196. class CommandStart(Command):
  197. command = "start"
  198. help = "start container"
  199. def run(
  200. self,
  201. *,
  202. container: BorgmaticContainer,
  203. data_sources: list[Path],
  204. secret_sources: list[Secret],
  205. **kwargs,
  206. ):
  207. container.run(data_sources, secret_sources)
  208. class CommandRm(Command):
  209. command = "rm"
  210. help = "remove container"
  211. def run(self, *, container: BorgmaticContainer, **kwargs):
  212. container.rm()
  213. class CommandBash(Command):
  214. command = "bash"
  215. help = "run shell in container"
  216. def run(self, *, container: BorgmaticContainer, **kwargs):
  217. container.exec(["bash"])
  218. class CommandCreateRepo(Command):
  219. command = "create_repo"
  220. help = "create repository"
  221. env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
  222. def run(self, *, container: BorgmaticContainer, **kwargs):
  223. container.exec(
  224. ["borgmatic", "repo-create", "--encryption", "repokey"], self.env_vars
  225. )
  226. class CommandExportKey(Command):
  227. command = "export_key"
  228. help = "export the repository key"
  229. env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
  230. def run(self, *, container: BorgmaticContainer, **kwargs):
  231. container.exec(["borgmatic", "export", "key"], self.env_vars)
  232. class CommandCreateSecrets(Command):
  233. command = "create_secrets"
  234. help = "create podman secrets"
  235. def run(self, *, secret_sources: list[Secret], **kwargs):
  236. keepass = KeePass.new(self.keepass_path)
  237. for s in secret_sources:
  238. s.create(keepass)
  239. @classmethod
  240. def init_subparser(cls, p):
  241. p.add_argument("keepass_path", type=Path, help="Path to the keepass")
  242. def main():
  243. login = os.getlogin()
  244. hostname = socket.gethostname()
  245. secret_sources_file = Path(f"./secret_sources_{hostname}_{login}")
  246. secret_sources = Secret.read_sources(secret_sources_file)
  247. data_sources_file = Path(f"./data_sources_{hostname}_{login}")
  248. data_sources = read_data_sources(data_sources_file)
  249. if not secret_sources:
  250. print("no secret required ?")
  251. container = BorgmaticContainer.new(hostname, login)
  252. parser = CliArguments.new()
  253. command = CliArguments.read_command(parser)
  254. command.run(
  255. secret_sources=secret_sources,
  256. data_sources=data_sources,
  257. container=container,
  258. )
  259. if __name__ == "__main__":
  260. main()