This repository has been archived by the owner on Dec 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
276 lines (207 loc) · 9.97 KB
/
config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
import optparse
import os
import re
import sys
import mod_plugins
import mod_logger
log = mod_logger.initlog(__name__)
def splitIntoList(value):
if len(value) == 0: return []
elif value.count(',') == 0: return [value]
else: return value.split(',')
def getDistributionFamily():
if os.path.isfile("/etc/redhat-release"):
return "redhat"
elif os.path.isfile("/etc/os-release"):
return "debian"
else:
return "unknown"
def convertType(name, value, vartype):
ret = False
value = value.strip()
try:
if vartype == "list": ret = splitIntoList(value)
elif len(value) == 0: ret = False
elif vartype == "int": ret = int(value)
elif vartype == "float": ret = float(value)
else: ret = str(value)
except ValueError:
log.fatal("Parameter '%s' should be a %s" % (name, vartype))
return ret
def checkValue(name, value, check):
if not check: return True
elif "(value)" in check: return eval(check)
elif type(value) == str: return eval("\"%s\" %s" % (value, check))
else: return eval("%.1f %s" % (value, check))
def checkNonEmptyList(value):
return len(value) != 0
def checkDrbdResources(resources):
global drbd_dir
RE_DRBD_RESOURCE = re.compile("^[\ \t]*resource[\ \t]+([a-z0-9]+).*$")
resources_dup = list(resources)
for res in glob.glob("%s/*.res" % (drbd_dir)):
resource = False
for line in open(res).readlines():
match = RE_DRBD_RESOURCE.match(line)
if match:
resource = match.group(1)
if resources.count(resource):
resources_dup.remove(resource)
if len(resources_dup):
log.fatal("The following DRBD resources do not exist: %s" % (resources_dup))
return True
def checkServices(services):
distro = getDistributionFamily()
if distro == "debian":
rcd = "/etc/rc2.d/S*"
cmd = "update-rc.d -f remove %s"
elif distro == "redhat":
rcd = "/etc/rc.d/rc3.d/S*"
cmd = "chkconfig %s off"
else:
rcd = False
for service in services:
initd = os.path.join("/etc/init.d", service)
disablecmd = cmd % service
if not os.path.isfile(initd):
log.fatal("Service '%s' does not exist" % (service))
elif rcd:
found = False
inode = os.stat(initd).st_ino
for rc in glob.glob(rcd):
if inode == os.stat(rc).st_ino:
# we have found a 'start' symlink
found = True
break
if found:
log.warning("Service '%s' is already enabled at boot" % (service))
log.info("If you want to disable it, you can use '%s'" % (disablecmd))
log.fatal("Service '%s' cannot be managed by koublad" % (service))
return True
def checkQuorumPlugin(filepath):
global config_dict
if not filepath:
return True
return os.path.isfile(os.path.join(config_dict['plugin_dir'], "quorum", "%s.py" % filepath)) or log.fatal("Quorum plugin '%s' does not exist." % (filepath))
def checkSwitcherPlugin(filepath):
global config_dict
if not filepath:
return True
return os.path.isfile(os.path.join(config_dict['plugin_dir'], "switcher", "%s.py" % filepath)) or log.fatal("Switcher plugin '%s' does not exist." % (filepath))
def checkNotifierPlugin(filepath):
global config_dict
if not filepath:
return True
return os.path.isfile(os.path.join(config_dict['plugin_dir'], "notifier", "%s.py" % filepath)) or log.fatal("Notifier plugin '%s' does not exist." % (filepath))
def checkFile(filepath):
return os.path.isfile(filepath) or log.fatal("File '%s' does not exist." % (filepath))
def checkDirectory(dirpath):
return os.path.isdir(dirpath) or log.fatal("Directory '%s' does not exist." % (dirpath))
def defaultVariables(config_checks):
config_dict = dict()
for name in config_checks.keys():
config_dict[name] = config_checks[name]['default']
return config_dict
def parseConfigurationFile(config_file, config_checks, config_optional, config_dict, plugin_name=False):
RE_CONFIG_LINE = re.compile("^[\ \t]*()([a-zA-Z0-9_]+)[\ \t]*=[\ \t]*([^#\n\r]+).*$")
RE_CONFIG_LINE_P = re.compile("^[\ \t]*([a-zA-Z0-9_]+)\.([a-zA-Z0-9_]+)[\ \t]*=[\ \t]*([^#\n\r]+).*$")
if not os.path.isfile(config_file):
log.fatal("Configuration file '%s' does not exist." % (config_file))
for line in open(config_file).readlines():
if plugin_name:
match = RE_CONFIG_LINE_P.match(line)
else:
match = RE_CONFIG_LINE.match(line)
if match:
plugin = match.group(1)
name = match.group(2).strip()
value = match.group(3).replace('\t', '').replace(' ', '').strip()
if plugin_name and plugin != plugin_name:
print "non-matching plugin %s -- %s" % (plugin, plugin_name)
if name in config_checks.keys():
vartype = config_checks[name]['type']
check = config_checks[name]['check']
config_dict[name] = convertType(name, value, vartype)
res = checkValue(name, config_dict[name], check)
if not res:
log.fatal("Parameter '%s' validation failed (%s)" % (name, check))
# check mandatory variables
for name in config_checks.keys():
if name not in config_optional and config_dict[name] == False:
log.fatal("Parameter '%s' cannot be empty or unset" % (name))
return config_dict
def show(data=False):
global config_dict
if not data:
data = config_dict
keys = data.keys()
keys.sort()
for name in keys:
print "%-16s: %s" % (name, data[name])
print
def parse_cmdline():
parser = optparse.OptionParser()
parser.add_option("--drbd-dir", dest="drbd_dir",
help="force specific DRBD directory", metavar="FILE", default="/etc/drbd.d")
parser.add_option("-c", "--config", dest="config",
help="Uses specified config file", metavar="FILE", default="/etc/koublad.conf")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="Do not print status messages to stderr")
parser.add_option("-d", "--no-daemonize",
action="store_false", dest="daemonize", default=True,
help="Do not start as a daemon (keep process attached to current TTY)")
parser.add_option("-p", "--pid-file", dest="pid_file",
help="set the PID file", metavar="FILE", default="/var/run/koublad.pid")
return parser.parse_args()
def parse():
global options
options, args = parse_cmdline()
global config_file
config_file = options.config
global drbd_dir
drbd_dir = options.drbd_dir
global config_dict
config_dict = dict()
config_checks = {
"port": { "type": "int", "default": 4997, "check": "> 1024" },
"role": { "type": "str", "default": False, "check": "in ['master', 'slave']" },
"initdead": { "type": "float", "default": 5.0, "check": "> 0.0" },
"peer_host": { "type": "str", "default": False, "check": False },
"peer_port": { "type": "int", "default": False, "check": "> 1024" },
"timeout": { "type": "float", "default": 2.0, "check": ">= 0.1" },
"interval": { "type": "float", "default": 0.2, "check": ">= 0.2" },
"services": { "type": "list", "default": [], "check": "checkServices(value)" },
"drbd_resources": { "type": "list", "default": [], "check": "checkDrbdResources(value)" },
"plugin_dir": { "type": "str", "default": "plugins/", "check": "checkDirectory(value)" },
"quorum_plugin": { "type": "str", "default": False, "check": "checkQuorumPlugin(value)" },
"switcher_plugin": { "type": "str", "default": False, "check": "checkSwitcherPlugin(value)" },
"filelog_filename": { "type": "str", "default": False, "check": "is not False" },
"filelog_level": { "type": "str", "default": False, "check": "in ['debug','info','warning','critical']" },
"syslog_level": { "type": "str", "default": False, "check": "in ['debug','info','warning','critical']" },
"syslog_facility": { "type": "str", "default": False, "check": "in ['auth', 'authpriv', 'cron', 'daemon',"
"'ftp', 'kern', 'lpr', 'mail', 'news',"
"'syslog', 'user', 'uucp', 'local0', 'local1',"
"'local2', 'local3', 'local4', 'local5',"
"'local6', 'local7']" },
"verbosity": { "type": "str", "default": False, "check": "in ['debug','info','warning','critical']" },
"notifier_plugin": { "type": "str", "default": False, "check": "checkNotifierPlugin(value)" },
}
config_optional = [
"quorum_plugin",
"switcher_plugin",
"notifier_plugin",
]
# set default values
config_dict = defaultVariables(config_checks)
# parse configuration file
config_dict = parseConfigurationFile(config_file, config_checks, config_optional, config_dict)
# set variable globaly
for name in config_checks.keys():
exec("globals()['%s'] = config_dict[name]" % (name))
# search for plugins
mod_plugins.search(plugin_dir)
mod_logger.configMainLogger()