summaryrefslogtreecommitdiffstats
path: root/src/lib/Server/Plugins/Metadata.py
blob: 81fcba223503f6de396a273a40a282cc6d2f63be (plain)
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
'''This file stores persistent metadata for the BCFG Configuration Repository'''
__revision__ = '$Revision$'

import lxml.etree, re, socket
import Bcfg2.Server.Plugin

class MetadataConsistencyError(Exception):
    '''This error gets raised when metadata is internally inconsistent'''
    pass

class MetadataRuntimeError(Exception):
    '''This error is raised when the metadata engine is called prior to reading enough data'''
    pass

class ClientMetadata(object):
    '''This object contains client metadata'''
    def __init__(self, client, groups, bundles, toolset, categories, probed):
        self.hostname = client
        self.bundles = bundles
        self.groups = groups
        self.toolset = toolset
        self.categories = categories
        self.probes = probed

    def inGroup(self, group):
        '''Test to see if client is a member of group'''
        return group in self.groups

class Metadata(Bcfg2.Server.Plugin.Plugin):
    '''This class contains data for bcfg2 server metadata'''
    __version__ = '$Id$'
    __author__ = 'bcfg-dev@mcs.anl.gov'
    __name__ = "Metadata"

    def __init__(self, core, datastore):
        Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)
        self.__name__ = 'Metadata'
        core.fam.AddMonitor("%s/%s" % (self.data, "groups.xml"), self)
        core.fam.AddMonitor("%s/%s" % (self.data, "clients.xml"), self)
        self.states = {'groups.xml':False, 'clients.xml':False}
        self.addresses = {}
        self.clients = {}
        self.aliases = {}
        self.groups = {}
        self.cgroups = {}
        self.public = []
        self.profiles = []
        self.toolsets = {}
        self.categories = {}
        self.bad_clients = {}
        self.clientdata = None
        self.default = None
        try:
            self.probes = Bcfg2.Server.Plugin.DirectoryBacked(datastore + "/Probes",
                                                              core.fam)
        except:
            self.probes = False
        self.probedata = {}
        self.extra = {'groups.xml':[], 'clients.xml':[]}

    def HandleEvent(self, event):
        '''Handle update events for data files'''
        filename = event.filename.split('/')[-1]
        if filename in ['groups.xml', 'clients.xml']:
            dest = filename
        elif filename in reduce(lambda x,y:x+y, self.extra.values()):
            if event.code2str() == 'exists':
                return
            dest = [key for key, value in self.extra.iteritems() if filename in value][0]
        else:
            return
        if event.code2str() == 'endExist':
            return
        try:
            xdata = lxml.etree.parse("%s/%s" % (self.data, dest))
        except lxml.etree.XMLSyntaxError:
            self.logger.error('Failed to parse %s' % (dest))
            return
        included = [ent.get('href') for ent in \
                    xdata.findall('./{http://www.w3.org/2001/XInclude}include')]
        if included:
            for name in included:
                if name not in self.extra[dest]:
                    self.core.fam.AddMonitor("%s/%s" % (self.data, name), self)
                    self.extra[dest].append(name)
            try:
                xdata.xinclude()
            except lxml.etree.XIncludeError:
                self.logger.error("Failed to process XInclude for file %s" % dest)

        if dest == 'clients.xml':
            self.clients = {}
            self.aliases = {}
            self.bad_clients = {}
            self.clientdata = xdata
            for client in xdata.findall('.//Client'):
                if 'address' in client.attrib:
                    self.addresses[client.get('address')] = client.get('name')
                for alias in [alias for alias in client.findall('Alias') if 'address' in alias.attrib]:
                    self.addresses[alias.get('address')] = client.get('name')
                    
                self.clients.update({client.get('name'): client.get('profile')})
                [self.aliases.update({alias.get('name'): client.get('name')}) for alias in client.findall('Alias')]
        elif dest == 'groups.xml':
            self.public = []
            self.profiles = []
            self.toolsets = {}
            self.groups = {}
            grouptmp = {}
            self.categories = {}
            for group in xdata.findall('.//Group'):
                if group.getparent().tag == 'Group':
                    continue
                grouptmp[group.get('name')] = tuple([[item.get('name') for item in group.findall(spec)]
                                                     for spec in ['./Bundle', './Group']])
                grouptmp[group.get('name')][1].append(group.get('name'))
                if group.get('default', 'false') == 'true':
                    self.default = group.get('name')
                if group.get('profile', 'false') == 'true':
                    self.profiles.append(group.get('name'))
                if group.get('public', 'false') == 'true':
                    self.public.append(group.get('name'))
                if group.attrib.has_key('toolset'):
                    self.toolsets[group.get('name')] = group.get('toolset')
                if group.attrib.has_key('category'):
                    self.categories[group.get('name')] = group.get('category')
            for group in grouptmp:
                # self.groups[group] => (bundles, groups, categories)
                self.groups[group] = ([], [], {})
                tocheck = [group]
                while tocheck:
                    now = tocheck.pop()
                    if now not in self.groups[group][1]:
                        self.groups[group][1].append(now)
                    if grouptmp.has_key(now):
                        (bundles, groups) = grouptmp[now]
                        for ggg in [ggg for ggg in groups if ggg not in self.groups[group][1]]:
                            if not self.categories.has_key(ggg) or not self.groups[group][2].has_key(self.categories[ggg]):
                                self.groups[group][1].append(ggg)
                                tocheck.append(ggg)
                            if self.categories.has_key(ggg):
                                self.groups[group][2][self.categories[ggg]] = ggg
                        [self.groups[group][0].append(bund) for bund in bundles
                         if bund not in self.groups[group][0]]
        self.states[dest] = True
        if False not in self.states.values():
            # check that all client groups are real and complete
            real = self.groups.keys()
            for client in self.clients.keys():
                if self.clients[client] not in self.profiles:
                    self.logger.error("Client %s set as nonexistant or incomplete group %s" \
                                      % (client, self.clients[client]))
                    self.logger.error("Removing client mapping for %s" % (client))
                    self.bad_clients[client] = self.clients[client]
                    del self.clients[client]
            for bclient in self.bad_clients.keys():
                if self.bad_clients[bclient] in self.profiles:
                    self.logger.info("Restored profile mapping for client %s" % bclient)
                    self.clients[bclient] = self.bad_clients[bclient]
                    del self.bad_clients[bclient]

    def set_profile(self, client, profile):
        '''Set group parameter for provided client'''
        self.logger.info("Asserting client %s profile to %s" % (client, profile))
        if False in self.states.values():
            raise MetadataRuntimeError
        if profile not in self.public:
            self.logger.error("Failed to set client %s to private group %s" % (client, profile))
            raise MetadataConsistencyError
        if self.clients.has_key(client):
            self.logger.info("Changing %s group from %s to %s" % (client, self.clients[client], profile))
            cli = self.clientdata.xpath('/Clients/Client[@name="%s"]' % (client))
            cli[0].set('profile', profile)
        else:
            lxml.etree.SubElement(self.clientdata.getroot(), 'Client', name=client, profile=profile)
        self.clients[client] = profile
        self.write_back_clients()

    def write_back_clients(self):
        '''Write changes to client.xml back to disk'''
        try:
            datafile = open("%s/%s" % (self.data, 'clients.xml'), 'w')
        except IOError:
            self.logger.error("Failed to write clients.xml")
            raise MetadataRuntimeError
        datafile.write(lxml.etree.tostring(self.clientdata.getroot()))
        datafile.close()

    def find_toolset(self, client):
        '''Find the toolset for a given client'''
        tgroups = [self.toolsets[group] for group in self.groups[client][1] if self.toolsets.has_key(group)]
        if len(tgroups) == 1:
            return tgroups[0]
        elif len(tgroups) == 0:
            self.logger.error("Couldn't find toolset for client %s" % (client))
            raise MetadataConsistencyError
        else:
            self.logger.error("Got goofy toolset result for client %s" % (client))
            raise MetadataConsistencyError

    def get_config_template(self, client):
        '''Build the configuration header for a client configuration'''
        return lxml.etree.Element("Configuration", version='2.0', toolset=self.find_toolset(client))

    def resolve_client(self, address):
        '''Lookup address locally or in DNS to get a hostname'''
        if self.addresses.has_key(address):
            return self.addresses[address]
        try:
            return socket.gethostbyaddr(address)[0]
        except socket.herror:
            warning = "address resolution error for %s" % (address)
            self.logger.warning(warning)
            raise MetadataConsistencyError
    
    def get_metadata(self, client):
        '''Return the metadata for a given client'''
        if self.aliases.has_key(client):
            client = self.aliases[client]
        if self.clients.has_key(client):
            (bundles, groups, categories) = self.groups[self.clients[client]]
        else:
            if self.default == None:
                self.logger.error("Cannot set group for client %s; no default group set" % (client))
                raise MetadataConsistencyError
            self.set_profile(client, self.default)
            [bundles, groups, categories] = self.groups[self.default]
        toolinfo = [self.toolsets[group] for group in groups if self.toolsets.has_key(group)]
        if len(toolinfo) > 1:
            self.logger.error("Found multiple toolsets for client %s; choosing one" % (client))
        elif len(toolinfo) == 0:
            self.logger.error("Cannot determine toolset for client %s" % (client))
            raise MetadataConsistencyError
        toolset = toolinfo[0]
        probed = self.probedata.get(client, {})
        newgroups = groups[:]
        newbundles = bundles[:]
        newcategories = {}
        newcategories.update(categories)
        for group in  self.cgroups.get(client, []):
            if self.groups.has_key(group):
                nbundles, ngroups, ncategories = self.groups[group]
            else:
                nbundles, ngroups, ncategories = ([], [group], {})
            [newbundles.append(b) for b in nbundles if b not in newbundles]
            [newgroups.append(g) for g in ngroups if g not in newgroups]
            newcategories.update(ncategories)
        return ClientMetadata(client, newgroups, newbundles, toolset, newcategories, probed)
        
    def GetProbes(self, _):
        '''Return a set of probes for execution on client'''
        ret = []
        if self.probes:
            bangline = re.compile('^#!(?P<interpreter>(/\w+)+)$')
            for name, entry in [(name, entry) for name, entry in \
                                self.probes.entries.iteritems() if entry.data]:
                probe = lxml.etree.Element('probe')
                probe.set('name', name )
                probe.set('source', self.__name__)
                probe.text = entry.data
                match = bangline.match(entry.data.split('\n')[0])
                if match:
                    probe.set('interpreter', match.group('interpreter'))
                else:
                    probe.set('interpreter', '/bin/sh')
                    ret.append(probe)
        return ret

    def ReceiveData(self, client, data):
        '''Receive probe results pertaining to client'''
        if not self.cgroups.has_key(client.hostname):
            self.cgroups[client.hostname] = []
        dlines = data.text.split('\n')
        for line in dlines[:]:
            if line.split(':')[0] == 'group':
                newgroup = line.split(':')[1].strip()
                if newgroup not in self.cgroups[client.hostname]:
                    self.cgroups[client.hostname].append(newgroup)
                dlines.remove(line)
        dtext = "\n".join(dlines)
        try:
            self.probedata[client.hostname].update({ data.get('name'):dtext })
        except KeyError:
            self.probedata[client.hostname] = { data.get('name'):dtext }