1 """ Common housekeeping for all daemons """
3 from configparser import ConfigParser, SectionProxy
4 from getopt import getopt
5 from logging import Formatter, getLogger, Logger, 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 from typing import Any, Dict, List, Optional, Tuple, Union
11 CONF = "/etc/loctrkd.conf"
13 DBFN = "/var/lib/loctrkd/loctrkd.sqlite"
16 version = get_distribution("loctrkd").version
17 except DistributionNotFound:
22 log: Logger, opts: Optional[List[Tuple[str, str]]] = None
25 opts, _ = getopt(argv[1:], "c:d")
27 conf = readconfig(dopts["-c"] if "-c" in dopts else CONF)
28 log.setLevel(DEBUG if "-d" in dopts else INFO)
30 fhdl = StreamHandler(stderr)
32 Formatter("%(asctime)s - %(levelname)s - %(message)s")
35 log.debug("%s starting with options: %s", version, dopts)
37 lhdl = SysLogHandler(address="/dev/log")
39 Formatter("%(name)s[%(process)d]: %(levelname)s - %(message)s")
42 log.info("%s starting with options: %s", version, dopts)
46 def readconfig(fname: str) -> ConfigParser:
47 config = ConfigParser()
48 config["collector"] = {
54 config["termconfig"] = {}
59 def normconf(section: SectionProxy) -> Dict[str, Any]:
60 result: Dict[str, Any] = {}
61 for key, val in section.items():
62 vals = val.split("\n")
63 if len(vals) > 1 and vals[0] == "":
65 lst: List[Union[str, int]] = []
68 lst.append(int(el, 0))
70 if el[0] == '"' and el[-1] == '"':
71 el = el.strip('"').rstrip('"')
74 all([isinstance(x, int) for x in lst])
75 or all([isinstance(x, str) for x in lst])
78 "Values of %s - %s are of different type", key, vals
87 if __name__ == "__main__":
90 def _print_config(conf: ConfigParser) -> None:
91 for section in conf.sections():
92 print("section", section)
93 for option in conf.options(section):
94 print(" ", option, conf[section][option])
96 conf = readconfig(argv[1])
98 print(normconf(conf["termconfig"]))