]> www.average.org Git - loctrkd.git/blob - gps303/common.py
09fb01f060c73c0f0821ec84947fb435fa1344da
[loctrkd.git] / gps303 / common.py
1 """ Common housekeeping for all daemons """
2
3 from configparser import ConfigParser
4 from getopt import getopt
5 from logging import getLogger, StreamHandler, DEBUG, INFO
6 from logging.handlers import SysLogHandler
7 from sys import argv, stderr, stdout
8
9 CONF = "/etc/gps303.conf"
10 PORT = 4303
11 DBFN = "/var/lib/gps303/gps303.sqlite"
12
13
14 def init(log, opts=None):
15     if opts is None:
16         opts, _ = getopt(argv[1:], "c:d")
17     opts = dict(opts)
18     conf = readconfig(opts["-c"] if "-c" in opts else CONF)
19     if stdout.isatty():
20         log.addHandler(StreamHandler(stderr))
21     else:
22         log.addHandler(SysLogHandler(address="/dev/log"))
23     log.setLevel(DEBUG if "-d" in opts else INFO)
24     log.info("starting with options: %s", opts)
25     return conf
26
27
28 def readconfig(fname):
29     config = ConfigParser()
30     config["collector"] = {
31         "port": PORT,
32     }
33     config["storage"] = {
34         "dbfn": DBFN,
35     }
36     config["termconfig"] = {}
37     config.read(fname)
38     return config
39
40
41 def normconf(section):
42     result = {}
43     for key, val in section.items():
44         vals = val.split("\n")
45         if len(vals) > 1 and vals[0] == "":
46             vals = vals[1:]
47         lst = []
48         for el in vals:
49             try:
50                 el = int(el, 0)
51             except ValueError:
52                 if el[0] == '"' and el[-1] == '"':
53                     el = el.strip('"').rstrip('"')
54             lst.append(el)
55         if len(lst) == 1:
56             [lst] = lst
57         result[key] = lst
58     return result
59
60
61 if __name__ == "__main__":
62     from sys import argv
63
64     def _print_config(conf):
65         for section in conf.sections():
66             print("section", section)
67             for option in conf.options(section):
68                 print("    ", option, conf[section][option])
69
70     conf = readconfig(argv[1])
71     _print_config(conf)
72     print(normconf(conf["termconfig"]))