summaryrefslogtreecommitdiffstats
path: root/src/lib/Server/Plugins/Cfg.py
blob: 184bb792c7c62e903dc698f12caaf33ef8f1b6f8 (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
"""This module implements a config file repository."""
__revision__ = '$Revision$'

import binascii
import logging
import lxml
import os
import re
import tempfile

import Bcfg2.Server.Plugin

try:
    import genshi.core
    import genshi.input
    from genshi.template import TemplateLoader, \
                                TextTemplate, MarkupTemplate, TemplateError
    from genshi.template import NewTextTemplate
    have_genshi = True
except:
    have_genshi = False

logger = logging.getLogger('Bcfg2.Plugins.Cfg')


# snipped from TGenshi
def removecomment(stream):
    """A genshi filter that removes comments from the stream."""
    for kind, data, pos in stream:
        if kind is genshi.core.COMMENT:
            continue
        yield kind, data, pos


def process_delta(data, delta):
    if not delta.specific.delta:
        return data
    if delta.specific.delta == 'cat':
        datalines = data.split('\n')
        for line in delta.data.split('\n'):
            if not line:
                continue
            if line[0] == '+':
                datalines.append(line[1:])
            elif line[0] == '-':
                if line[1:] in datalines:
                    datalines.remove(line[1:])
        return "\n".join(datalines)
    elif delta.specific.delta == 'diff':
        basehandle, basename = tempfile.mkstemp()
        basefile = open(basename, 'w')
        basefile.write(data)
        basefile.close()
        os.close(basehandle)
        dhandle, dname = tempfile.mkstemp()
        dfile = open(dname, 'w')
        dfile.write(delta.data)
        dfile.close()
        os.close(dhandle)
        ret = os.system("patch -uf %s < %s > /dev/null 2>&1" \
                        % (basefile.name, dfile.name))
        output = open(basefile.name, 'r').read()
        [os.unlink(fname) for fname in [basefile.name, dfile.name]]
        if ret >> 8 != 0:
            raise Bcfg2.Server.Plugin.PluginExecutionError, ('delta', delta)
        return output


class CfgMatcher:

    def __init__(self, fname):
        name = re.escape(fname)
        self.basefile_reg = re.compile('^(?P<basename>%s)(|\\.H_(?P<hostname>\S+?)|.G(?P<prio>\d+)_(?P<group>\S+?))(?P<genshi>\\.genshi)?$' % name)
        self.delta_reg = re.compile('^(?P<basename>%s)(|\\.H_(?P<hostname>\S+)|\\.G(?P<prio>\d+)_(?P<group>\S+))\\.(?P<delta>(cat|diff))$' % name)
        self.cat_count = fname.count(".cat")
        self.diff_count = fname.count(".diff")

    def match(self, fname):
        if fname.count(".cat") > self.cat_count \
               or fname.count('.diff') > self.diff_count:
            return self.delta_reg.match(fname)
        return self.basefile_reg.match(fname)


class CfgEntrySet(Bcfg2.Server.Plugin.EntrySet):

    def __init__(self, basename, path, entry_type, encoding):
        Bcfg2.Server.Plugin.EntrySet.__init__(self, basename, path,
                                              entry_type, encoding)
        self.specific = CfgMatcher(path.split('/')[-1])

    def sort_by_specific(self, one, other):
        return cmp(one.specific, other.specific)

    def get_pertinent_entries(self, metadata):
        """return a list of all entries pertinent
        to a client => [base, delta1, delta2]
        """
        matching = [ent for ent in self.entries.values() if \
                    ent.specific.matches(metadata)]
        matching.sort(self.sort_by_specific)
        non_delta = [matching.index(m) for m in matching
                     if not m.specific.delta]
        if not non_delta:
            raise Bcfg2.Server.Plugin.PluginExecutionError
        base = min(non_delta)
        used = matching[:base + 1]
        used.reverse()
        return used

    def bind_entry(self, entry, metadata):
        self.bind_info_to_entry(entry, metadata)
        used = self.get_pertinent_entries(metadata)
        basefile = used.pop(0)
        if entry.tag == 'Path':
            entry.set('type', 'file')
        if basefile.name.endswith(".genshi"):
            if not have_genshi:
                logger.error("Cfg: Genshi is not available")
                raise Bcfg2.Server.Plugin.PluginExecutionError
            try:
                template_cls = NewTextTemplate
                loader = TemplateLoader()
                template = loader.load(basefile.name, cls=template_cls,
                                       encoding=self.encoding)
                fname = entry.get('realname', entry.get('name'))
                stream = template.generate(name=fname,
                                           metadata=metadata,
                                           path=basefile.name).filter(removecomment)
                try:
                    data = stream.render('text', strip_whitespace=False)
                except TypeError:
                    data = stream.render('text')
                if data == '':
                    entry.set('empty', 'true')
            except Exception, e:
                logger.error("Cfg: genshi exception: %s" % e)
                raise Bcfg2.Server.Plugin.PluginExecutionError
        else:
            data = basefile.data
            for delta in used:
                data = data.strip()
                data = process_delta(data, delta)
            if used:
                data += '\n'
        if entry.get('encoding') == 'base64':
            entry.text = binascii.b2a_base64(data)
        else:
            try:
                entry.text = unicode(data, self.encoding)
            except UnicodeDecodeError, e:
                logger.error("Failed to decode %s: %s" % (entry.get('name'), e))
                logger.error("Please verify you are using the proper encoding.")
                raise Bcfg2.Server.Plugin.PluginExecutionError
        if entry.text in ['', None]:
            entry.set('empty', 'true')

    def list_accept_choices(self, metadata):
        '''return a list of candidate pull locations'''
        used = self.get_pertinent_entries(metadata)
        ret = []
        if used:
            ret.append(used[0].specific)
        if not ret[0].hostname:
            ret.append(Bcfg2.Server.Plugin.Specificity(hostname=metadata.hostname))
        return ret

    def build_filename(self, specific):
        bfname = self.path + '/' + self.path.split('/')[-1]
        if specific.all:
            return bfname
        elif specific.group:
            return "%s.G%d_%s" % (bfname, specific.prio, specific.group)
        elif specific.hostname:
            return "%s.H_%s" % (bfname, specific.hostname)

    def write_update(self, specific, new_entry, log):
        if 'text' in new_entry:
            name = self.build_filename(specific)
            if name.endswith(".genshi"):
                logger.error("Cfg: Unable to pull data for genshi types")
                raise PluginExecutionError
            open(name, 'w').write(new_entry['text'])
            if log:
                logger.info("Wrote file %s" % name)
        badattr = [attr for attr in ['owner', 'group', 'perms']
                   if attr in new_entry]
        if badattr:
            metadata_updates = {}
            metadata_updates.update(self.metadata)
            for attr in badattr:
                metadata_updates[attr] = new_entry.get(attr)
            infoxml = lxml.etree.Element('FileInfo')
            infotag = lxml.etree.SubElement(infoxml, 'Info')
            [infotag.attrib.__setitem__(attr, metadata_updates[attr]) \
                for attr in metadata_updates]
            ofile = open(self.path + "/info.xml", "w")
            ofile.write(lxml.etree.tostring(infoxml, pretty_print=True))
            ofile.close()
            if log:
                logger.info("Wrote file %s" % (self.path + "/info.xml"))


class Cfg(Bcfg2.Server.Plugin.GroupSpool,
          Bcfg2.Server.Plugin.PullTarget):
    """This generator in the configuration file repository for Bcfg2."""
    name = 'Cfg'
    __version__ = '$Id$'
    __author__ = 'bcfg-dev@mcs.anl.gov'
    es_cls = CfgEntrySet
    es_child_cls = Bcfg2.Server.Plugin.SpecificData

    def AcceptChoices(self, entry, metadata):
        return self.entries[entry.get('name')].list_accept_choices(metadata)

    def AcceptPullData(self, specific, new_entry, log):
        return self.entries[new_entry.get('name')].write_update(specific,
                                                                new_entry,
                                                                log)