]> mj.ucw.cz Git - pynsc.git/blob - nsconfig/daemon/bind.py
Top-of-file comments
[pynsc.git] / nsconfig / daemon / bind.py
1 # PyNSC: Generator of configuration for BIND 9
2 # (c) 2024 Martin Mareš <mj@ucw.cz>
3
4 from pathlib import Path
5 import sys
6 from typing import TextIO
7
8 from nsconfig.core import NscZone, NscZonePrimary, NscZoneSecondary, NscZoneAlias
9 from nsconfig.daemon import NscDaemon
10
11
12 class NscDaemonBind(NscDaemon):
13     config_path: Path
14     control_command: str
15     need_full_reload: bool
16
17     def __init__(self,
18                  config_file: str = 'named.conf.nsc',
19                  control_command: str = 'rndc') -> None:
20         super().__init__()
21         self.config_path = Path(config_file)
22         self.control_command = control_command
23         self.need_full_reload = False
24
25     def dump_config(self, file: TextIO = sys.stdout) -> None:
26         file.write('# Domains managed by NSC\n')
27         file.write('# This file was automatically generated by NSC, please do not edit manually.\n\n')
28         for z in self.nsc.get_zones():
29             file.write(f'zone "{z.name}" in {{\n')  # broken editor: }}
30             if isinstance(z, NscZonePrimary) or isinstance(z, NscZoneAlias):
31                 file.write('\ttype master;\n')
32                 file.write(f'\tfile "{z.zone_file}";\n')
33             elif isinstance(z, NscZoneSecondary):
34                 file.write('\ttype slave;\n')
35                 file.write(f'\tfile "{z.secondary_file}";\n')
36                 file.write(f'\tmasters {{ {z.primary_server}; }};\n')
37             else:
38                 raise NotImplementedError()
39             for opt in z.config.daemon_options:
40                 file.write(f'\t{opt}\n')
41             file.write('}\n\n')
42
43     def write_config(self) -> None:
44         if self._write_config(self.config_path):
45             self.need_full_reload = True
46
47     def reload_zone(self, z: NscZone) -> None:
48         if (isinstance(z, NscZonePrimary) or isinstance(z, NscZoneAlias)) and not self.need_full_reload:
49             print(f'Reloading zone {z.name}')
50             self._run_command([self.control_command, 'reload', z.name])
51
52     def reload_daemon(self) -> None:
53         if self.need_full_reload:
54             print('Reloading daemon')
55             self._run_command([self.control_command, 'reload'])