]> www.average.org Git - loctrkd.git/blob - gps303/common.py
Do not write startup message for command-line cmds
[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 Formatter, getLogger, StreamHandler, DEBUG, INFO
6 from logging.handlers import SysLogHandler
7 from pkg_resources import get_distribution, DistributionNotFound
8 from sys import argv, stderr, stdout
9
10 CONF = "/etc/gps303.conf"
11 PORT = 4303
12 DBFN = "/var/lib/gps303/gps303.sqlite"
13
14 try:
15     version = get_distribution("gps303").version
16 except DistributionNotFound:
17     version = "<local>"
18
19
20 def init(log, opts=None):
21     if opts is None:
22         opts, _ = getopt(argv[1:], "c:d")
23     opts = dict(opts)
24     conf = readconfig(opts["-c"] if "-c" in opts else CONF)
25     log.setLevel(DEBUG if "-d" in opts else INFO)
26     if stdout.isatty():
27         hdl = StreamHandler(stderr)
28         hdl.setFormatter(
29             Formatter("%(asctime)s - %(levelname)s - %(message)s")
30         )
31         log.addHandler(hdl)
32         log.debug("%s starting with options: %s", version, opts)
33     else:
34         hdl = SysLogHandler(address="/dev/log")
35         hdl.setFormatter(
36             Formatter("%(name)s[%(process)d]: %(levelname)s - %(message)s")
37         )
38         log.addHandler(hdl)
39         log.info("%s starting with options: %s", version, opts)
40     return conf
41
42
43 def readconfig(fname):
44     config = ConfigParser()
45     config["collector"] = {
46         "port": PORT,
47     }
48     config["storage"] = {
49         "dbfn": DBFN,
50     }
51     config["termconfig"] = {}
52     config.read(fname)
53     return config
54
55
56 def normconf(section):
57     result = {}
58     for key, val in section.items():
59         vals = val.split("\n")
60         if len(vals) > 1 and vals[0] == "":
61             vals = vals[1:]
62         lst = []
63         for el in vals:
64             try:
65                 el = int(el, 0)
66             except ValueError:
67                 if el[0] == '"' and el[-1] == '"':
68                     el = el.strip('"').rstrip('"')
69             lst.append(el)
70         if len(lst) == 1:
71             [lst] = lst
72         result[key] = lst
73     return result
74
75
76 if __name__ == "__main__":
77     from sys import argv
78
79     def _print_config(conf):
80         for section in conf.sections():
81             print("section", section)
82             for option in conf.options(section):
83                 print("    ", option, conf[section][option])
84
85     conf = readconfig(argv[1])
86     _print_config(conf)
87     print(normconf(conf["termconfig"]))