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