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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
|
#!/usr/bin/env python
"""Bcfg2 Client"""
import fcntl
import logging
import os
import signal
import socket
import stat
import sys
import tempfile
import time
import Bcfg2.Options
import Bcfg2.Client.XML
import Bcfg2.Client.Frame
import Bcfg2.Client.Tools
# Compatibility imports
from Bcfg2.Bcfg2Py3k import xmlrpclib
from Bcfg2.version import __version__
import Bcfg2.Proxy
import Bcfg2.Logger
logger = logging.getLogger('bcfg2')
def cb_sigint_handler(signum, frame):
"""Exit upon CTRL-C."""
os._exit(1)
class Client:
"""The main bcfg2 client class"""
def __init__(self):
self.toolset = None
self.config = None
optinfo = Bcfg2.Options.CLIENT_COMMON_OPTIONS
self.setup = Bcfg2.Options.OptionParser(optinfo)
self.setup.parse(sys.argv[1:])
if self.setup['args']:
print("Bcfg2 takes no arguments, only options")
print(self.setup.buildHelpMessage())
raise SystemExit(1)
if self.setup['debug']:
level = logging.DEBUG
elif self.setup['verbose']:
level = logging.INFO
else:
level = logging.WARNING
Bcfg2.Logger.setup_logging('bcfg2',
to_syslog=self.setup['syslog'],
level=level,
to_file=self.setup['logging'])
self.logger = logging.getLogger('bcfg2')
self.logger.debug(self.setup)
if self.setup['bundle_quick']:
if not self.setup['bundle'] and not self.setup['skipbundle']:
self.logger.error("-Q option requires -b or -B")
raise SystemExit(1)
elif self.setup['remove']:
self.logger.error("-Q option incompatible with -r")
raise SystemExit(1)
if 'drivers' in self.setup and self.setup['drivers'] == 'help':
self.logger.info("The following drivers are available:")
self.logger.info(Bcfg2.Client.Tools.drivers)
raise SystemExit(0)
if self.setup['remove'] and 'services' in self.setup['remove'].lower():
self.logger.error("Service removal is nonsensical; "
"removed services will only be disabled")
if (self.setup['remove'] and
self.setup['remove'].lower() not in ['all', 'services',
'packages']):
self.logger.error("Got unknown argument %s for -r" %
self.setup['remove'])
if self.setup["file"] and self.setup["cache"]:
print("cannot use -f and -c together")
raise SystemExit(1)
if not self.setup['server'].startswith('https://'):
self.setup['server'] = 'https://' + self.setup['server']
def run_probe(self, probe):
"""Execute probe."""
name = probe.get('name')
self.logger.info("Running probe %s" % name)
ret = Bcfg2.Client.XML.Element("probe-data",
name=name,
source=probe.get('source'))
try:
scripthandle, scriptname = tempfile.mkstemp()
script = open(scriptname, 'w+')
try:
script.write("#!%s\n" %
(probe.attrib.get('interpreter', '/bin/sh')))
script.write(probe.text)
script.close()
os.close(scripthandle)
os.chmod(script.name,
stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH |
stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH |
stat.S_IWUSR) # 0755
ret.text = os.popen(script.name).read().strip()
self.logger.info("Probe %s has result:" % name)
self.logger.info(ret.text)
finally:
os.unlink(script.name)
except:
self.logger.error("Failed to execute probe: %s" % (name), exc_info=1)
raise SystemExit(1)
return ret
def fatal_error(self, message):
"""Signal a fatal error."""
self.logger.error("Fatal error: %s" % (message))
os._exit(1)
def run(self):
"""Perform client execution phase."""
times = {}
# begin configuration
times['start'] = time.time()
self.logger.info("Starting Bcfg2 client run at %s" % times['start'])
if self.setup['file']:
# read config from file
try:
self.logger.debug("Reading cached configuration from %s" %
(self.setup['file']))
configfile = open(self.setup['file'], 'r')
rawconfig = configfile.read()
configfile.close()
except IOError:
self.fatal_error("Failed to read cached configuration from: %s"
% (self.setup['file']))
return(1)
else:
# retrieve config from server
proxy = Bcfg2.Proxy.ComponentProxy(self.setup['server'],
self.setup['user'],
self.setup['password'],
key=self.setup['key'],
cert=self.setup['certificate'],
ca=self.setup['ca'],
allowedServerCNs=self.setup['serverCN'],
timeout=self.setup['timeout'])
if self.setup['profile']:
try:
proxy.AssertProfile(self.setup['profile'])
except Bcfg2.Proxy.ProxyError:
err = sys.exc_info()[1]
self.fatal_error("Failed to set client profile")
self.logger.error(str(err))
raise SystemExit(1)
try:
probe_data = proxy.DeclareVersion(__version__)
except xmlrpclib.Fault:
err = sys.exc_info()[1]
if (err.faultCode == xmlrpclib.METHOD_NOT_FOUND or
(err.faultCode == 7 and
err.faultString.startswith("Unknown method"))):
self.logger.debug("Server does not support declaring "
"client version")
else:
self.logger.error("Failed to declare version: %s" % err)
except (Bcfg2.Proxy.ProxyError,
Bcfg2.Proxy.CertificateError,
socket.gaierror,
socket.error):
err = sys.exc_info()[1]
self.logger.error("Failed to declare version: %s" % err)
try:
probe_data = proxy.GetProbes()
except (Bcfg2.Proxy.ProxyError,
Bcfg2.Proxy.CertificateError,
socket.gaierror,
socket.error):
err = sys.exc_info()[1]
self.logger.error("Failed to download probes from bcfg2: %s" %
err)
raise SystemExit(1)
times['probe_download'] = time.time()
try:
probes = Bcfg2.Client.XML.XML(str(probe_data))
except Bcfg2.Client.XML.ParseError:
syntax_error = sys.exc_info()[1]
self.fatal_error(
"Server returned invalid probe requests: %s" %
(syntax_error))
return(1)
# execute probes
try:
probedata = Bcfg2.Client.XML.Element("ProbeData")
[probedata.append(self.run_probe(probe))
for probe in probes.findall(".//probe")]
except:
self.logger.error("Failed to execute probes")
raise SystemExit(1)
if len(probes.findall(".//probe")) > 0:
try:
# upload probe responses
proxy.RecvProbeData(Bcfg2.Client.XML.tostring(probedata,
encoding='unicode'))
except Bcfg2.Proxy.ProxyError:
err = sys.exc_info()[1]
self.logger.error("Failed to upload probe data: %s" % err)
raise SystemExit(1)
times['probe_upload'] = time.time()
if self.setup['decision'] in ['whitelist', 'blacklist']:
try:
self.setup['decision_list'] = \
proxy.GetDecisionList(self.setup['decision'])
self.logger.info("Got decision list from server:")
self.logger.info(self.setup['decision_list'])
except Bcfg2.Proxy.ProxyError:
err = sys.exc_info()[1]
self.logger.error("Failed to get decision list: %s" % err)
raise SystemExit(1)
try:
rawconfig = proxy.GetConfig().encode('UTF-8')
except Bcfg2.Proxy.ProxyError:
err = sys.exc_info()[1]
self.logger.error("Failed to download configuration from "
"Bcfg2: %s" % err)
raise SystemExit(2)
times['config_download'] = time.time()
if self.setup['cache']:
try:
open(self.setup['cache'], 'w').write(rawconfig)
os.chmod(self.setup['cache'], 33152)
except IOError:
self.logger.warning("Failed to write config cache file %s" %
(self.setup['cache']))
times['caching'] = time.time()
try:
self.config = Bcfg2.Client.XML.XML(rawconfig)
except Bcfg2.Client.XML.ParseError:
syntax_error = sys.exc_info()[1]
self.fatal_error("The configuration could not be parsed: %s" %
(syntax_error))
return(1)
times['config_parse'] = time.time()
if self.config.tag == 'error':
self.fatal_error("Server error: %s" % (self.config.text))
return(1)
if self.setup['bundle_quick']:
newconfig = Bcfg2.Client.XML.XML('<Configuration/>')
[newconfig.append(bundle)
for bundle in self.config.getchildren()
if (bundle.tag == 'Bundle' and
((self.setup['bundle'] and
bundle.get('name') in self.setup['bundle']) or
(self.setup['skipbundle'] and
bundle.get('name') not in self.setup['skipbundle'])))]
self.config = newconfig
self.tools = Bcfg2.Client.Frame.Frame(self.config,
self.setup,
times, self.setup['drivers'],
self.setup['dryrun'])
if not self.setup['omit_lock_check']:
#check lock here
try:
lockfile = open(self.setup['lockfile'], 'w')
try:
fcntl.lockf(lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
#otherwise exit and give a warning to the user
self.fatal_error("An other instance of Bcfg2 is running. If you what to bypass the check, run with %s option" %
(Bcfg2.Options.OMIT_LOCK_CHECK.cmd))
except:
lockfile = None
self.logger.error("Failed to open lockfile")
# execute the said configuration
self.tools.Execute()
if not self.setup['omit_lock_check']:
#unlock here
if lockfile:
try:
fcntl.lockf(lockfile.fileno(), fcntl.LOCK_UN)
os.remove(self.setup['lockfile'])
except OSError:
self.logger.error("Failed to unlock lockfile %s" % lockfile.name)
if not self.setup['file'] and not self.setup['bundle_quick']:
# upload statistics
feedback = self.tools.GenerateStats()
try:
proxy.RecvStats(Bcfg2.Client.XML.tostring(feedback,
encoding='unicode'))
except Bcfg2.Proxy.ProxyError:
err = sys.exc_info()[1]
self.logger.error("Failed to upload configuration statistics: "
"%s" % err)
raise SystemExit(2)
self.logger.info("Finished Bcfg2 client run at %s" % time.time())
if __name__ == '__main__':
signal.signal(signal.SIGINT, cb_sigint_handler)
client = Client()
spid = os.getpid()
client.run()
|