summaryrefslogtreecommitdiffstats
path: root/src/lib/Bcfg2/Server/Plugins/Cfg/CfgGenshiGenerator.py
blob: c3bf9569bfc8a8cd5113f4b12c51de7c88e27ad3 (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
""" The CfgGenshiGenerator allows you to use the `Genshi
<http://genshi.edgewall.org>`_ templating system to generate
:ref:`server-plugins-generators-cfg` files. """

import re
import sys
import traceback
import Bcfg2.Options
from Bcfg2.Server.Plugin import PluginExecutionError, removecomment, \
    DefaultTemplateDataProvider, get_template_data
from Bcfg2.Server.Plugins.Cfg import CfgGenerator
from genshi.template import TemplateLoader, NewTextTemplate
from genshi.template.base import TemplateError
from genshi.template.eval import UndefinedError, Suite


def _genshi_removes_blank_lines():
    """ Genshi 0.5 uses the Python :mod:`compiler` package to
    compile genshi snippets to AST.  Genshi 0.6 uses some bespoke
    magic, because compiler has been deprecated.
    :func:`compiler.parse` produces an AST that removes all excess
    whitespace (e.g., blank lines), while
    :func:`genshi.template.astutil.parse` does not.  In order to
    determine which actual line of code an error occurs on, we
    need to know which is in use and how it treats blank lines.
    I've beat my head against this for hours and the best/only way
    I can find is to compile some genshi code with an error and
    see which line it's on."""
    code = """d = dict()
d['a']"""
    try:
        Suite(code).execute(dict())
    except KeyError:
        line = traceback.extract_tb(sys.exc_info()[2])[-1][1]
        if line == 2:
            return True
        else:
            return False

#: True if Genshi removes all blank lines from a code block before
#: executing it; False indicates that Genshi only removes leading
#: and trailing blank lines. See
#: :func:`_genshi_removes_blank_lines` for an explanation of this.
GENSHI_REMOVES_BLANK_LINES = _genshi_removes_blank_lines()


class DefaultGenshiDataProvider(DefaultTemplateDataProvider):
    """ Template data provider for Genshi templates. Cheetah and
    Genshi currently differ over the value of the ``path`` variable,
    which is why this is necessary. """

    def get_template_data(self, entry, metadata, template):
        rv = DefaultTemplateDataProvider.get_template_data(self, entry,
                                                           metadata, template)
        rv['path'] = template
        return rv


class CfgGenshiGenerator(CfgGenerator):
    """ The CfgGenshiGenerator allows you to use the `Genshi
    <http://genshi.edgewall.org>`_ templating system to generate
    :ref:`server-plugins-generators-cfg` files. """

    #: Handle .genshi files
    __extensions__ = ['genshi']

    #: ``__loader_cls__`` is the class that will be instantiated to
    #: load the template files.  It must implement one public function,
    #: ``load()``, as :class:`genshi.template.TemplateLoader`.
    __loader_cls__ = TemplateLoader

    #: Ignore ``.genshi_include`` files so they can be used with the
    #: Genshi ``{% include ... %}`` directive without raising warnings.
    __ignore__ = ["genshi_include"]

    #: Low priority to avoid matching host- or group-specific
    #: .crypt.genshi files
    __priority__ = 50

    #: Error-handling in Genshi is pretty obtuse.  This regex is used
    #: to extract the first line of the code block that raised an
    #: exception in a Genshi template so we can provide a decent error
    #: message that actually tells the end user where an error
    #: occurred.
    pyerror_re = re.compile(r'<\w+ u?[\'"](.*?)\s*\.\.\.[\'"]>')

    def __init__(self, fname, spec):
        CfgGenerator.__init__(self, fname, spec)
        self.template = None
        self.loader = self.__loader_cls__(max_cache_size=0)
    __init__.__doc__ = CfgGenerator.__init__.__doc__

    def get_data(self, entry, metadata):
        if self.template is None:
            raise PluginExecutionError("Failed to load template %s" %
                                       self.name)

        stream = self.template.generate(
            **get_template_data(
                entry, metadata, self.name,
                default=DefaultGenshiDataProvider())).filter(removecomment)
        try:
            try:
                return stream.render('text',
                                     encoding=Bcfg2.Options.setup.encoding,
                                     strip_whitespace=False)
            except TypeError:
                return stream.render('text',
                                     encoding=Bcfg2.Options.setup.encoding)
        except UndefinedError:
            # a failure in a genshi expression _other_ than %{ python ... %}
            err = sys.exc_info()[1]
            stack = traceback.extract_tb(sys.exc_info()[2])
            for quad in stack:
                if quad[0] == self.name:
                    raise PluginExecutionError("%s: %s at '%s'" %
                                               (err.__class__.__name__, err,
                                                quad[2]))
            raise
        except:
            # this needs to be a blanket except, since it can catch
            # any error raised by the genshi template.
            self._handle_genshi_exception(sys.exc_info())
    get_data.__doc__ = CfgGenerator.get_data.__doc__

    def _handle_genshi_exception(self, exc):
        """ this is horrible, and I deeply apologize to whoever gets
        to maintain this after I go to the Great Beer Garden in the
        Sky.  genshi is incredibly opaque about what's being executed,
        so the only way I can find to determine which {% python %}
        block is being executed -- if there are multiples -- is to
        iterate through them and match the snippet of the first line
        that's in the traceback with the first non-empty line of the
        block. """

        # a failure in a %{ python ... %} block -- the snippet in
        # the traceback is just the beginning of the block.
        err = exc[1]
        stack = traceback.extract_tb(exc[2])

        # find the right frame of the stack
        for frame in reversed(stack):
            if frame[0] == self.name:
                lineno, func = frame[1:3]
                break
        else:
            # couldn't even find the stack frame, wtf.
            raise PluginExecutionError("%s: %s" %
                                       (err.__class__.__name__, err))

        execs = [contents
                 for etype, contents, _ in self.template.stream
                 if etype == self.template.EXEC]
        contents = None
        if len(execs) == 1:
            contents = execs[0]
        elif len(execs) > 1:
            match = self.pyerror_re.match(func)
            if match:
                firstline = match.group(0)
                for pyblock in execs:
                    if pyblock.startswith(firstline):
                        contents = pyblock
                        break
        # else, no EXEC blocks -- WTF?
        if contents:
            # we now have the bogus block, but we need to get the
            # offending line.  To get there, we do (line number given
            # in the exception) - (firstlineno from the internal
            # genshi code object of the snippet) = (line number of the
            # line with an error within the block, with blank lines
            # removed as appropriate for
            # :attr:`GENSHI_REMOVES_BLANK_LINES`)
            code = contents.source.strip().splitlines()
            if GENSHI_REMOVES_BLANK_LINES:
                code = [l for l in code if l.strip()]
            try:
                line = code[lineno - contents.code.co_firstlineno]
                raise PluginExecutionError("%s: %s at '%s'" %
                                           (err.__class__.__name__, err,
                                            line))
            except IndexError:
                raise PluginExecutionError("%s: %s" %
                                           (err.__class__.__name__, err))
        raise

    def handle_event(self, event):
        CfgGenerator.handle_event(self, event)
        try:
            self.template = self.loader.load(
                self.name, cls=NewTextTemplate,
                encoding=Bcfg2.Options.setup.encoding)
        except TemplateError:
            raise PluginExecutionError("Failed to load template: %s" %
                                       sys.exc_info()[1])
    handle_event.__doc__ = CfgGenerator.handle_event.__doc__