]> mj.ucw.cz Git - pynsc.git/blob - nsconfig/cli.py
Beautify
[pynsc.git] / nsconfig / cli.py
1 import argparse
2 from pathlib import Path
3 from texttable import Texttable
4
5 from nsconfig.core import Nsc, ZoneType
6
7
8 def do_test(nsc: Nsc) -> None:
9     test_dir = Path('test')
10     test_dir.mkdir(exist_ok=True)
11     for z in nsc.get_zones():
12         print(f'Zone:        {z.name}')
13         print(f'Type:        {z.zone_type.name}')
14         if z.zone_type == ZoneType.primary:
15             print(f'Old serial:  {z.prev_state.serial}')
16             print(f'Old hash:    {z.prev_state.hash}')
17             print(f'New serial:  {z.state.serial}')
18             print(f'New hash:    {z.state.hash}')
19             out_file = test_dir / z.safe_name
20             print(f'Dumping to:  {out_file}')
21             with open(out_file, 'w') as f:
22                 z.dump(file=f)
23         else:
24             print(f'Primary:     {z.primary_server}')
25         print()
26
27
28 def do_status(nsc: Nsc) -> None:
29     table = Texttable(max_width=0)
30     table.header(['Zone', 'Old serial', 'Old hash', 'New serial', 'New hash', 'S'])
31     table.set_cols_dtype(['t', 'i', 't', 'i', 't', 't'])
32     table.set_deco(Texttable.HEADER)
33
34     for z in nsc.get_zones():
35         if z.zone_type != ZoneType.primary:
36             table.add_row([z.name, 'secondary', "", "", "", ""])
37             continue
38         if z.state.serial == z.prev_state.serial:
39             action = ""
40         else:
41             action = '*'
42         table.add_row([
43             z.name,
44             z.prev_state.serial,
45             z.prev_state.hash,
46             z.state.serial,
47             z.state.hash,
48             action,
49         ])
50
51     print(table.draw())
52
53
54 def do_update(nsc: Nsc) -> None:
55     for z in nsc.get_zones():
56         if z.zone_type == ZoneType.primary and z.state.serial != z.prev_state.serial:
57             print(f'Updating zone {z.name} (serial {z.state.serial})')
58             z.write_zone()
59             z.write_state()
60
61
62 def main(nsc: Nsc) -> None:
63     parser = argparse.ArgumentParser(description='Configure name server')
64     subparsers = parser.add_subparsers(help='action to perform', dest='action', required=True, metavar='ACTION')
65
66     test_parser = subparsers.add_parser('test', help='test new configuration', description='Test new configuration')
67
68     status_parser = subparsers.add_parser('status', help='list status of zones', description='List status of zones')
69
70     update_parser = subparsers.add_parser('update', help='update configuration', description='Update zone files and daemon configuration as needed')
71
72     args = parser.parse_args()
73
74     nsc.process()
75
76     if args.action == 'test':
77         do_test(nsc)
78     elif args.action == 'status':
79         do_status(nsc)
80     elif args.action == 'update':
81         do_update(nsc)