1 | # -*- coding: utf-8 -*- |
---|
2 | # |
---|
3 | # Copyright (C) 2007-2010 Edgewall Software |
---|
4 | # Copyright (C) 2005-2007 Christopher Lenz <cmlenz@gmx.de> |
---|
5 | # All rights reserved. |
---|
6 | # |
---|
7 | # This software is licensed as described in the file COPYING, which |
---|
8 | # you should have received as part of this distribution. The terms |
---|
9 | # are also available at http://bitten.edgewall.org/wiki/License. |
---|
10 | |
---|
11 | """Execution of build recipes. |
---|
12 | |
---|
13 | This module provides various classes that can be used to process build recipes, |
---|
14 | most importantly the `Recipe` class. |
---|
15 | """ |
---|
16 | |
---|
17 | import inspect |
---|
18 | import keyword |
---|
19 | import logging |
---|
20 | import os |
---|
21 | import time |
---|
22 | try: |
---|
23 | set |
---|
24 | except NameError: |
---|
25 | from sets import Set as set |
---|
26 | |
---|
27 | from pkg_resources import WorkingSet |
---|
28 | from bitten.build import BuildError, TimeoutError |
---|
29 | from bitten.build.config import Configuration |
---|
30 | from bitten.util import xmlio |
---|
31 | |
---|
32 | __all__ = ['Context', 'Recipe', 'Step', 'InvalidRecipeError'] |
---|
33 | __docformat__ = 'restructuredtext en' |
---|
34 | |
---|
35 | log = logging.getLogger('bitten.recipe') |
---|
36 | |
---|
37 | |
---|
38 | class InvalidRecipeError(Exception): |
---|
39 | """Exception raised when a recipe is not valid.""" |
---|
40 | |
---|
41 | |
---|
42 | class Context(object): |
---|
43 | """The context in which a build is executed.""" |
---|
44 | |
---|
45 | step = None # The current step |
---|
46 | generator = None # The current generator (namespace#name) |
---|
47 | |
---|
48 | def __init__(self, basedir, config=None, vars=None): |
---|
49 | """Initialize the context. |
---|
50 | |
---|
51 | :param basedir: a string containing the working directory for the build. |
---|
52 | (may be a pattern for replacement ex: 'build_${build}' |
---|
53 | :param config: the build slave configuration |
---|
54 | :type config: `Configuration` |
---|
55 | """ |
---|
56 | self.config = config or Configuration() |
---|
57 | self.vars = vars or {} |
---|
58 | self.output = [] |
---|
59 | self.basedir = os.path.realpath(self.config.interpolate(basedir, |
---|
60 | **self.vars)) |
---|
61 | self.vars['basedir'] = self.basedir.replace('\\', '\\\\') |
---|
62 | |
---|
63 | def run(self, step, namespace, name, attr): |
---|
64 | """Run the specified recipe command. |
---|
65 | |
---|
66 | :param step: the build step that the command belongs to |
---|
67 | :param namespace: the namespace URI of the command |
---|
68 | :param name: the local tag name of the command |
---|
69 | :param attr: a dictionary containing the attributes defined on the |
---|
70 | command element |
---|
71 | """ |
---|
72 | self.step = step |
---|
73 | |
---|
74 | try: |
---|
75 | function = None |
---|
76 | qname = '#'.join(filter(None, [namespace, name])) |
---|
77 | if namespace: |
---|
78 | group = 'bitten.recipe_commands' |
---|
79 | for entry_point in WorkingSet().iter_entry_points(group, qname): |
---|
80 | function = entry_point.load() |
---|
81 | break |
---|
82 | elif name == 'report': |
---|
83 | function = Context.report_file |
---|
84 | elif name == 'attach': |
---|
85 | function = Context.attach |
---|
86 | if not function: |
---|
87 | raise InvalidRecipeError('Unknown recipe command %s' % qname) |
---|
88 | |
---|
89 | def escape(name): |
---|
90 | name = name.replace('-', '_') |
---|
91 | if keyword.iskeyword(name) or name in __builtins__: |
---|
92 | name = name + '_' |
---|
93 | return name |
---|
94 | args = dict([(escape(name), |
---|
95 | self.config.interpolate(attr[name], **self.vars)) |
---|
96 | for name in attr]) |
---|
97 | function_args, has_kwargs = inspect.getargspec(function)[0:3:2] |
---|
98 | for arg in args: |
---|
99 | if not (arg in function_args or has_kwargs): |
---|
100 | raise InvalidRecipeError( |
---|
101 | "Unsupported argument '%s' for command %s" % \ |
---|
102 | (arg, qname)) |
---|
103 | |
---|
104 | self.generator = qname |
---|
105 | log.debug('Executing %s with arguments: %s', function, args) |
---|
106 | function(self, **args) |
---|
107 | |
---|
108 | finally: |
---|
109 | self.generator = None |
---|
110 | self.step = None |
---|
111 | |
---|
112 | def error(self, message): |
---|
113 | """Record an error message. |
---|
114 | |
---|
115 | :param message: a string containing the error message. |
---|
116 | """ |
---|
117 | self.output.append((Recipe.ERROR, None, self.generator, message)) |
---|
118 | |
---|
119 | def log(self, xml): |
---|
120 | """Record log output. |
---|
121 | |
---|
122 | :param xml: an XML fragment containing the log messages |
---|
123 | """ |
---|
124 | self.output.append((Recipe.LOG, None, self.generator, xml)) |
---|
125 | |
---|
126 | def report(self, category, xml): |
---|
127 | """Record report data. |
---|
128 | |
---|
129 | :param category: the name of category of the report |
---|
130 | :param xml: an XML fragment containing the report data |
---|
131 | """ |
---|
132 | self.output.append((Recipe.REPORT, category, self.generator, xml)) |
---|
133 | |
---|
134 | def report_file(self, category=None, file_=None): |
---|
135 | """Read report data from a file and record it. |
---|
136 | |
---|
137 | :param category: the name of the category of the report |
---|
138 | :param file\_: the path to the file containing the report data, relative |
---|
139 | to the base directory |
---|
140 | """ |
---|
141 | filename = self.resolve(file_) |
---|
142 | try: |
---|
143 | fileobj = file(filename, 'r') |
---|
144 | try: |
---|
145 | xml_elem = xmlio.Fragment() |
---|
146 | for child in xmlio.parse(fileobj).children(): |
---|
147 | child_elem = xmlio.Element(child.name, **dict([ |
---|
148 | (name, value) for name, value in child.attr.items() |
---|
149 | if value is not None |
---|
150 | ])) |
---|
151 | xml_elem.append(child_elem[ |
---|
152 | [xmlio.Element(grandchild.name)[grandchild.gettext()] |
---|
153 | for grandchild in child.children()] |
---|
154 | ]) |
---|
155 | self.output.append((Recipe.REPORT, category, None, xml_elem)) |
---|
156 | finally: |
---|
157 | fileobj.close() |
---|
158 | except xmlio.ParseError, e: |
---|
159 | self.error('Failed to parse %s report at %s: %s' |
---|
160 | % (category, filename, e)) |
---|
161 | except IOError, e: |
---|
162 | self.error('Failed to read %s report at %s: %s' |
---|
163 | % (category, filename, e)) |
---|
164 | |
---|
165 | def attach(self, file_=None, description=None, resource=None): |
---|
166 | """Attach a file to the build or build configuration. |
---|
167 | |
---|
168 | :param file\_: the path to the file to attach, relative to |
---|
169 | base directory. |
---|
170 | :param description: description saved with attachment |
---|
171 | :param resource: which resource to attach the file to, |
---|
172 | either 'build' (default) or 'config' |
---|
173 | """ |
---|
174 | # Attachments are not added as inline xml, so only adding |
---|
175 | # the details for later processing. |
---|
176 | if not file_: |
---|
177 | self.error('No attachment file specified.') |
---|
178 | return |
---|
179 | xml_elem = xmlio.Element('file', filename=file_, |
---|
180 | description=description or '', |
---|
181 | resource=resource or 'build') |
---|
182 | self.output.append((Recipe.ATTACH, None, None, xml_elem)) |
---|
183 | |
---|
184 | def resolve(self, *path): |
---|
185 | """Return the path of a file relative to the base directory. |
---|
186 | |
---|
187 | Accepts any number of positional arguments, which are joined using the |
---|
188 | system path separator to form the path. |
---|
189 | """ |
---|
190 | return os.path.normpath(os.path.join(self.basedir, *path)) |
---|
191 | |
---|
192 | |
---|
193 | class Step(object): |
---|
194 | """Represents a single step of a build recipe. |
---|
195 | |
---|
196 | Iterate over an object of this class to get the commands to execute, and |
---|
197 | their keyword arguments. |
---|
198 | """ |
---|
199 | |
---|
200 | def __init__(self, elem, onerror_default): |
---|
201 | """Create the step. |
---|
202 | |
---|
203 | :param elem: the XML element representing the step |
---|
204 | :type elem: `ParsedElement` |
---|
205 | """ |
---|
206 | self._elem = elem |
---|
207 | self.id = elem.attr['id'] |
---|
208 | self.description = elem.attr.get('description') |
---|
209 | self.onerror = elem.attr.get('onerror', onerror_default) |
---|
210 | assert self.onerror in ('fail', 'ignore', 'continue') |
---|
211 | |
---|
212 | def __repr__(self): |
---|
213 | return '<%s %r>' % (type(self).__name__, self.id) |
---|
214 | |
---|
215 | def execute(self, ctxt): |
---|
216 | """Execute this step in the given context. |
---|
217 | |
---|
218 | :param ctxt: the build context |
---|
219 | :type ctxt: `Context` |
---|
220 | """ |
---|
221 | last_finish = time.time() |
---|
222 | for child in self._elem: |
---|
223 | try: |
---|
224 | ctxt.run(self, child.namespace, child.name, child.attr) |
---|
225 | except (BuildError, InvalidRecipeError, TimeoutError), e: |
---|
226 | ctxt.error(e) |
---|
227 | if time.time() < last_finish + 1: |
---|
228 | # Add a delay to make sure steps appear in correct order |
---|
229 | time.sleep(1) |
---|
230 | |
---|
231 | errors = [] |
---|
232 | while ctxt.output: |
---|
233 | type, category, generator, output = ctxt.output.pop(0) |
---|
234 | yield type, category, generator, output |
---|
235 | if type == Recipe.ERROR: |
---|
236 | errors.append((generator, output)) |
---|
237 | if errors: |
---|
238 | for _t, error in errors: |
---|
239 | log.error(error) |
---|
240 | if self.onerror != 'ignore': |
---|
241 | raise BuildError("Build step '%s' failed" % self.id) |
---|
242 | log.warning("Continuing despite errors in step '%s'", self.id) |
---|
243 | |
---|
244 | |
---|
245 | class Recipe(object): |
---|
246 | """A build recipe. |
---|
247 | |
---|
248 | Iterate over this object to get the individual build steps in the order |
---|
249 | they have been defined in the recipe file. |
---|
250 | """ |
---|
251 | |
---|
252 | ERROR = 'error' |
---|
253 | LOG = 'log' |
---|
254 | REPORT = 'report' |
---|
255 | ATTACH = 'attach' |
---|
256 | |
---|
257 | def __init__(self, xml, basedir=None, config=None): |
---|
258 | """Create the recipe. |
---|
259 | |
---|
260 | :param xml: the XML document representing the recipe |
---|
261 | :type xml: `ParsedElement` |
---|
262 | :param basedir: the base directory for the build |
---|
263 | :param config: the slave configuration (optional) |
---|
264 | :type config: `Configuration` |
---|
265 | """ |
---|
266 | if basedir == None: |
---|
267 | basedir=os.getcwd() |
---|
268 | |
---|
269 | assert isinstance(xml, xmlio.ParsedElement) |
---|
270 | vars = dict([(name, value) for name, value in xml.attr.items() |
---|
271 | if not name.startswith('xmlns')]) |
---|
272 | self.ctxt = Context(basedir, config, vars) |
---|
273 | self._root = xml |
---|
274 | self.onerror_default = vars.get('onerror', 'fail') |
---|
275 | assert self.onerror_default in ('fail', 'ignore', 'continue') |
---|
276 | |
---|
277 | def __iter__(self): |
---|
278 | """Iterate over the individual steps of the recipe.""" |
---|
279 | for child in self._root.children('step'): |
---|
280 | yield Step(child, self.onerror_default) |
---|
281 | |
---|
282 | def validate(self): |
---|
283 | """Validate the recipe. |
---|
284 | |
---|
285 | This method checks a number of constraints: |
---|
286 | - the name of the root element must be "build" |
---|
287 | - the only permitted child elements or the root element with the name |
---|
288 | "step" |
---|
289 | - the recipe must contain at least one step |
---|
290 | - step elements must have a unique "id" attribute |
---|
291 | - a step must contain at least one nested command |
---|
292 | - commands must not have nested content |
---|
293 | |
---|
294 | :raise InvalidRecipeError: in case any of the above contraints is |
---|
295 | violated |
---|
296 | """ |
---|
297 | if self._root.name != 'build': |
---|
298 | raise InvalidRecipeError('Root element must be <build>') |
---|
299 | steps = list(self._root.children()) |
---|
300 | if not steps: |
---|
301 | raise InvalidRecipeError('Recipe defines no build steps') |
---|
302 | |
---|
303 | step_ids = set() |
---|
304 | for step in steps: |
---|
305 | if step.name != 'step': |
---|
306 | raise InvalidRecipeError('Only <step> elements allowed at ' |
---|
307 | 'top level of recipe') |
---|
308 | if not step.attr.get('id'): |
---|
309 | raise InvalidRecipeError('Steps must have an "id" attribute') |
---|
310 | |
---|
311 | if step.attr['id'] in step_ids: |
---|
312 | raise InvalidRecipeError('Duplicate step ID "%s"' % |
---|
313 | step.attr['id']) |
---|
314 | step_ids.add(step.attr['id']) |
---|
315 | |
---|
316 | cmds = list(step.children()) |
---|
317 | if not cmds: |
---|
318 | raise InvalidRecipeError('Step "%s" has no recipe commands' % |
---|
319 | step.attr['id']) |
---|
320 | for cmd in cmds: |
---|
321 | if len(list(cmd.children())): |
---|
322 | raise InvalidRecipeError('Recipe command <%s> has nested ' |
---|
323 | 'content' % cmd.name) |
---|