]> mj.ucw.cz Git - pynsc.git/blob - nsconfig/daemon/__init__.py
Top-of-file comments
[pynsc.git] / nsconfig / daemon / __init__.py
1 # PyNSC: Generic interface for generating daemon configuration
2 # (c) 2024 Martin Mareš <mj@ucw.cz>
3
4 from io import StringIO
5 from pathlib import Path
6 from typing import TextIO
7 import subprocess
8 import sys
9
10 from nsconfig.core import Nsc, NscZone
11
12
13 class NscDaemon:
14     nsc: Nsc
15
16     def __init__(self) -> None:
17         pass
18
19     def setup(self, nsc: Nsc) -> None:
20         self.nsc = nsc
21
22     def dump_config(self, file: TextIO = sys.stdout) -> None:
23         pass
24
25     def write_config(self) -> None:
26         pass
27
28     def reload_zone(self, z: NscZone) -> None:
29         pass
30
31     def reload_daemon(self) -> None:
32         pass
33
34     def _install_config(self, path: Path, new_contents: str) -> bool:
35         try:
36             old_new_contents = path.read_text()
37         except FileNotFoundError:
38             old_new_contents = None
39         if new_contents == old_new_contents:
40             return False
41         else:
42             new_path = Path(str(path) + '.new')
43             with open(new_path, 'w') as f:
44                 f.write(new_contents)
45             new_path.replace(path)
46             return True
47
48     def _write_config(self, config_path: Path) -> bool:
49         string_stream = StringIO()
50         self.dump_config(string_stream)
51         if self._install_config(config_path, string_stream.getvalue()):
52             print('Wrote new daemon configuration')
53             return True
54         else:
55             print('Daemon configuration not changed')
56             return False
57
58     def _run_command(self, argv, **kwargs) -> None:
59         res = subprocess.run(argv, **kwargs)
60         if res.returncode > 0:
61             print(f'Command failed: {argv}')
62             sys.exit(1)
63
64
65 class NscDaemonNull(NscDaemon):
66     pass