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
|
#!/usr/bin/env python
from getopt import getopt, GetoptError
from os import popen, chmod, unlink
from sys import argv, exit, exc_info
from string import join
from tempfile import mktemp
from traceback import extract_tb
from elementtree.ElementTree import Element, XML, tostring
from sss.ssslib import comm_lib
from Bcfg2.Client.Debian import Debian
def ElementMatch(master, sub):
if master.tag == sub.tag:
for k in sub.attrib.keys():
if master.attrib[k] != sub.attrib[k]:
return False
return True
return False
def RunProbe(probe):
ret = Element("probe-data", name=probe.attrib['name'], source=probe.attrib['source'])
script = open(mktemp(), 'w+')
script.write("#!%s\n"%(probe.attrib.get('interpreter', '/bin/sh')))
script.write(probe.text)
script.close()
chmod(script.name, 0755)
ret.text = popen(script.name).read()
unlink(script.name)
return ret
def dgetopt(arglist, opt, vopt):
r = {}
for o in opt.values() + vopt.values():
r[o] = False
gstr = join(opt.keys()) + join([x+':' for x in vopt.keys()])
try:
(o, a) = getopt(arglist, gstr)
except GetoptError, g:
print g
print "bcfg2 Usage:"
for (k,v) in opt.iteritems():
print " -%s %s"%(k,v)
for (k,v) in vopt.iteritems():
print " -%s <%s>"%(k,v)
exit(1)
for (gopt,garg) in o:
option = gopt[1:]
if opt.has_key(option):
r[opt[option]] = True
else:
r[vopt[option]] = garg
return r
class ClientState(object):
def __init__(self, cfg, setup):
self.states = {}
self.structures = {}
self.cfg = cfg
self.setup = setup
self.modified = []
self.extra = []
self.toolset = Debian(cfg, setup)
def LogFailure(self, area, entry):
print "Failure in %s for entry: %s"%(area, tostring(entry))
(t,v,tb) = exc_info()
for line in extract_tb(tb):
print "File %s, line %i, in %s\n %s\n"%(line)
print "%s: %s\n"%(t,v)
del t,v,tb
def VerifyEntry(self, entry, modlist = []):
try:
method = getattr(self.toolset, "Verify%s"%(entry.tag))
# verify state and stash value in state
if entry.tag == 'Package':
self.states[entry] = method(entry, modlist)
else:
self.states[entry] = method(entry)
if self.setup['debug']:
print entry.attrib['name'], self.states[entry]
except:
self.LogFailure("Verify", entry)
def InstallEntry(self, entry):
try:
method = getattr(self.toolset, "Install%s"%(entry.tag))
self.states[entry] = method(entry)
except:
self.LogFailure("Install", entry)
def Inventory(self):
# build initial set of states
unexamined = map(lambda x:(x,[]), self.cfg.getchildren())
while unexamined:
(r, modlist) = unexamined.pop()
if r.tag not in ['Bundle', 'Independant']:
self.VerifyEntry(r, modlist)
else:
modlist = [x.attrib['name'] for x in r.getchildren() if x.tag == 'ConfigFile']
unexamined += map(lambda x:(x,modlist), r.getchildren())
self.structures[r] = False
for structure in self.cfg.getchildren():
self.CheckStructure(structure)
# TwoWay: build list of "extra configs"
#e = self.toolset.FindElements()
#known = self.states.keys()
#for entry in e:
# if not filter(lambda x:ElementMatch(x, entry), known):
# self.extra.append(entry)
#print self.extra
def CheckStructure(self, structure):
if structure in self.modified:
self.modified.remove(structure)
if structure.tag == 'Bundle':
# check for clobbered data
modlist = [x.attrib['name'] for x in structure.getchildren() if x.tag == 'ConfigFile']
for entry in structure.getchildren():
self.VerifyEntry(entry, modlist)
try:
state = map(lambda x:self.states[x], structure.getchildren())
if False not in state:
self.structures[structure] = True
except KeyError, k:
print "State verify evidently failed for %s"%(k)
self.structures[structure] = False
def Install(self):
self.modified = [k for (k,v) in self.structures.iteritems() if not v]
for entry in [k for (k,v) in self.states.iteritems() if not v]:
self.InstallEntry(entry)
def Commit(self):
self.toolset.Commit()
if __name__ == '__main__':
# parse command line options
options = {'v':'verbose','q':'quick', 'd':'debug', 'n':'dryrun', 'B':'build', 'p':'paranoid'}
doptions = {'b':'bundle', 'f':'file', 'c':'cache', 'p':'profile', 'i':'image'}
setup = dgetopt(argv[1:], options, doptions)
print setup
# connect to bcfg2d
comm = comm_lib()
h = comm.ClientInit("bcfg2")
# get probes
comm.SendMessage(h, "<get-probes/>")
data = comm.RecvMessage(h)
#if setup['verbose']: print data
probes = XML(data)
# execute probes
probedata = map(RunProbe, probes.findall(".//probe"))
# upload probe responses
cpd = Element("probe-data")
map(lambda x:cpd.append(x), probedata)
if setup['verbose'] : print tostring(cpd)
comm.SendMessage(h, tostring(cpd))
r = comm.RecvMessage(h)
msg = Element("get-config")
if setup['profile']: msg.attrib['profile'] = setup['profile']
if setup['image']: msg.attrib['image'] = setup['image']
# get config
comm.SendMessage(h, tostring(msg))
r = comm.RecvMessage(h)
if setup['cache']:
try:
open(setup['cache'], 'w').write(r)
except:
print "failed to write config cache file %s"%(setup['cache'])
cfg = XML(r)
if cfg.tag == 'error':
print "got error from server"
exit(1)
client = ClientState(cfg, setup)
# verify state
client.Inventory()
# summarize current state
print "--> %s of %s config elements correct"%(client.states.values().count(True), len(client.states.values()))
# install incorrect aspects of configuration
client.Install()
# flush pending changes
client.Commit()
print "--> %s of %s config elements correct"%(client.states.values().count(True), len(client.states.values()))
print "bad:"
for k,v in client.states.iteritems():
if not v:
print "%s:%s"%(k.tag, k.attrib['name'])
# install config
# upload statistics
comm.ClientClose(h)
|