Debian Codegraph @

powa_collector/options.py

raw
1 """
2 Simple configuration file handling, as a JSON.
3 """
4 import json
5 import os
6 import sys
7
8
9 SAMPLE_CONFIG_FILE = """
10 {
11 "repository": {
12 "dsn": "postgresql://powa_user@localhost:5432/powa",
13 },
14 "use_server_alias": false
15 "debug": false
16 }
17
18 """
19
20 CONF_LOCATIONS = [
21 '/etc/powa-collector.conf',
22 os.path.expanduser('~/.config/powa-collector.conf'),
23 os.path.expanduser('~/.powa-collector.conf'),
24 './powa-collector.conf'
25 ]
26
27
28 def get_full_config(conn):
29 """Return the full configuration, consisting of the information from the local
30 configuration file and the remote servers stored on the repository
31 database.
32 """
33 return add_servers_config(conn, parse_options())
34
35
36 def add_servers_config(conn, config):
37 """Add the activated remote servers stored on the repository database to a
38 given configuration JSON.
39 """
40 if ("servers" not in config):
41 config["servers"] = {}
42
43 cur = conn.cursor()
44 cur.execute("""
45 SELECT id, hostname, port, username, password, dbname,
46 frequency, coalesce(alias, '') AS alias
47 FROM {powa}.powa_servers s
48 WHERE s.id > 0
49 AND s.frequency > 0
50 ORDER BY id
51 """)
52
53 for row in cur:
54 parms = {}
55 parms["host"] = row[1]
56 parms["port"] = row[2]
57 parms["user"] = row[3]
58 if (row[4] is not None):
59 parms["password"] = row[4]
60 parms["dbname"] = row[5]
61
62 key = row[1] + ':' + str(row[2])
63 config["servers"][key] = {}
64 config["servers"][key]["dsn"] = parms
65 config["servers"][key]["frequency"] = row[6]
66 if (config["use_server_alias"] and row[7] != ''):
67 config["servers"][key]["alias"] = row[7]
68 else:
69 config["servers"][key]["alias"] = key
70 config["servers"][key]["srvid"] = row[0]
71
72 conn.commit()
73
74 return config
75
76
77 def parse_options():
78 """Look for the configuration file in all supported location, parse it and
79 return the resulting JSON, also adding the implicit values if needed.
80 """
81 options = None
82
83 for possible_config in CONF_LOCATIONS:
84 options = parse_file(possible_config)
85 if (options is not None):
86 break
87
88 if (options is None):
89 print("Could not find the configuration file in any of the expected"
90 + " locations:")
91 for possible_config in CONF_LOCATIONS:
92 print("\t- %s" % possible_config)
93
94 sys.exit(1)
95
96 if ('repository' not in options or 'dsn' not in options["repository"]):
97 print("The configuration file is invalid, it should contains"
98 + " a repository.dsn entry")
99 print("Place and adapt the following content in one of those "
100 "locations:""")
101 print("\n\t".join([""] + CONF_LOCATIONS))
102 print(SAMPLE_CONFIG_FILE)
103 sys.exit(1)
104
105 for opt in ['use_server_alias', 'debug']:
106 if (opt not in options):
107 options[opt] = False
108
109 return options
110
111
112 def parse_file(filepath):
113 """Read a configuration file and return the JSON
114 """
115 try:
116 return json.load(open(filepath))
117 except IOError:
118 return None
119 except Exception as e:
120 print("Error parsing config file %s:" % filepath)
121 print("\t%s" % e)
122 sys.exit(1)