| 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. |
---|
1 | 15 | """ |
---|
| 16 | |
---|
1 | 17 | import inspect |
---|
1 | 18 | import keyword |
---|
1 | 19 | import logging |
---|
1 | 20 | import os |
---|
1 | 21 | import time |
---|
1 | 22 | try: |
---|
1 | 23 | set |
---|
0 | 24 | except NameError: |
---|
0 | 25 | from sets import Set as set |
---|
| 26 | |
---|
1 | 27 | from pkg_resources import WorkingSet |
---|
1 | 28 | from bitten.build import BuildError, TimeoutError |
---|
1 | 29 | from bitten.build.config import Configuration |
---|
1 | 30 | from bitten.util import xmlio |
---|
| 31 | |
---|
1 | 32 | __all__ = ['Context', 'Recipe', 'Step', 'InvalidRecipeError'] |
---|
1 | 33 | __docformat__ = 'restructuredtext en' |
---|
| 34 | |
---|
1 | 35 | log = logging.getLogger('bitten.recipe') |
---|
| 36 | |
---|
| 37 | |
---|
2 | 38 | class InvalidRecipeError(Exception): |
---|
1 | 39 | """Exception raised when a recipe is not valid.""" |
---|
| 40 | |
---|
| 41 | |
---|
2 | 42 | class Context(object): |
---|
1 | 43 | """The context in which a build is executed.""" |
---|
| 44 | |
---|
1 | 45 | step = None # The current step |
---|
1 | 46 | generator = None # The current generator (namespace#name) |
---|
| 47 | |
---|
1 | 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 | """ |
---|
78 | 56 | self.config = config or Configuration() |
---|
78 | 57 | self.vars = vars or {} |
---|
78 | 58 | self.output = [] |
---|
78 | 59 | self.basedir = os.path.realpath(self.config.interpolate(basedir, |
---|
78 | 60 | **self.vars)) |
---|
78 | 61 | self.vars['basedir'] = self.basedir.replace('\\', '\\\\') |
---|
| 62 | |
---|
1 | 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 | """ |
---|
3 | 72 | self.step = step |
---|
| 73 | |
---|
3 | 74 | try: |
---|
3 | 75 | function = None |
---|
3 | 76 | qname = '#'.join(filter(None, [namespace, name])) |
---|
3 | 77 | if namespace: |
---|
3 | 78 | group = 'bitten.recipe_commands' |
---|
3 | 79 | for entry_point in WorkingSet().iter_entry_points(group, qname): |
---|
3 | 80 | function = entry_point.load() |
---|
3 | 81 | break |
---|
0 | 82 | elif name == 'report': |
---|
0 | 83 | function = Context.report_file |
---|
0 | 84 | elif name == 'attach': |
---|
0 | 85 | function = Context.attach |
---|
3 | 86 | if not function: |
---|
0 | 87 | raise InvalidRecipeError('Unknown recipe command %s' % qname) |
---|
| 88 | |
---|
3 | 89 | def escape(name): |
---|
5 | 90 | name = name.replace('-', '_') |
---|
5 | 91 | if keyword.iskeyword(name) or name in __builtins__: |
---|
0 | 92 | name = name + '_' |
---|
5 | 93 | return name |
---|
3 | 94 | args = dict([(escape(name), |
---|
3 | 95 | self.config.interpolate(attr[name], **self.vars)) |
---|
8 | 96 | for name in attr]) |
---|
3 | 97 | function_args, has_kwargs = inspect.getargspec(function)[0:3:2] |
---|
7 | 98 | for arg in args: |
---|
5 | 99 | if not (arg in function_args or has_kwargs): |
---|
1 | 100 | raise InvalidRecipeError( |
---|
1 | 101 | "Unsupported argument '%s' for command %s" % \ |
---|
1 | 102 | (arg, qname)) |
---|
| 103 | |
---|
2 | 104 | self.generator = qname |
---|
2 | 105 | log.debug('Executing %s with arguments: %s', function, args) |
---|
2 | 106 | function(self, **args) |
---|
| 107 | |
---|
0 | 108 | finally: |
---|
3 | 109 | self.generator = None |
---|
3 | 110 | self.step = None |
---|
| 111 | |
---|
1 | 112 | def error(self, message): |
---|
| 113 | """Record an error message. |
---|
| 114 | |
---|
| 115 | :param message: a string containing the error message. |
---|
| 116 | """ |
---|
4 | 117 | self.output.append((Recipe.ERROR, None, self.generator, message)) |
---|
| 118 | |
---|
1 | 119 | def log(self, xml): |
---|
| 120 | """Record log output. |
---|
| 121 | |
---|
| 122 | :param xml: an XML fragment containing the log messages |
---|
| 123 | """ |
---|
4 | 124 | self.output.append((Recipe.LOG, None, self.generator, xml)) |
---|
| 125 | |
---|
1 | 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 | """ |
---|
34 | 132 | self.output.append((Recipe.REPORT, category, self.generator, xml)) |
---|
| 133 | |
---|
1 | 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 | """ |
---|
0 | 141 | filename = self.resolve(file_) |
---|
0 | 142 | try: |
---|
0 | 143 | fileobj = file(filename, 'r') |
---|
0 | 144 | try: |
---|
0 | 145 | xml_elem = xmlio.Fragment() |
---|
0 | 146 | for child in xmlio.parse(fileobj).children(): |
---|
0 | 147 | child_elem = xmlio.Element(child.name, **dict([ |
---|
0 | 148 | (name, value) for name, value in child.attr.items() |
---|
0 | 149 | if value is not None |
---|
0 | 150 | ])) |
---|
0 | 151 | xml_elem.append(child_elem[ |
---|
0 | 152 | [xmlio.Element(grandchild.name)[grandchild.gettext()] |
---|
0 | 153 | for grandchild in child.children()] |
---|
0 | 154 | ]) |
---|
0 | 155 | self.output.append((Recipe.REPORT, category, None, xml_elem)) |
---|
0 | 156 | finally: |
---|
0 | 157 | fileobj.close() |
---|
0 | 158 | except xmlio.ParseError, e: |
---|
0 | 159 | self.error('Failed to parse %s report at %s: %s' |
---|
0 | 160 | % (category, filename, e)) |
---|
0 | 161 | except IOError, e: |
---|
0 | 162 | self.error('Failed to read %s report at %s: %s' |
---|
0 | 163 | % (category, filename, e)) |
---|
| 164 | |
---|
1 | 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. |
---|
2 | 176 | if not file_: |
---|
0 | 177 | self.error('No attachment file specified.') |
---|
0 | 178 | return |
---|
2 | 179 | xml_elem = xmlio.Element('file', filename=file_, |
---|
2 | 180 | description=description or '', |
---|
2 | 181 | resource=resource or 'build') |
---|
2 | 182 | self.output.append((Recipe.ATTACH, None, None, xml_elem)) |
---|
| 183 | |
---|
1 | 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 | """ |
---|
55 | 190 | return os.path.normpath(os.path.join(self.basedir, *path)) |
---|
| 191 | |
---|
| 192 | |
---|
2 | 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. |
---|
1 | 198 | """ |
---|
| 199 | |
---|
1 | 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 | """ |
---|
22 | 206 | self._elem = elem |
---|
22 | 207 | self.id = elem.attr['id'] |
---|
22 | 208 | self.description = elem.attr.get('description') |
---|
22 | 209 | self.onerror = elem.attr.get('onerror', onerror_default) |
---|
22 | 210 | assert self.onerror in ('fail', 'ignore', 'continue') |
---|
| 211 | |
---|
1 | 212 | def __repr__(self): |
---|
0 | 213 | return '<%s %r>' % (type(self).__name__, self.id) |
---|
| 214 | |
---|
1 | 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 | """ |
---|
2 | 221 | last_finish = time.time() |
---|
4 | 222 | for child in self._elem: |
---|
2 | 223 | try: |
---|
2 | 224 | ctxt.run(self, child.namespace, child.name, child.attr) |
---|
0 | 225 | except (BuildError, InvalidRecipeError, TimeoutError), e: |
---|
0 | 226 | ctxt.error(e) |
---|
2 | 227 | if time.time() < last_finish + 1: |
---|
| 228 | # Add a delay to make sure steps appear in correct order |
---|
2 | 229 | time.sleep(1) |
---|
| 230 | |
---|
2 | 231 | errors = [] |
---|
4 | 232 | while ctxt.output: |
---|
2 | 233 | type, category, generator, output = ctxt.output.pop(0) |
---|
2 | 234 | yield type, category, generator, output |
---|
2 | 235 | if type == Recipe.ERROR: |
---|
0 | 236 | errors.append((generator, output)) |
---|
2 | 237 | if errors: |
---|
0 | 238 | for _t, error in errors: |
---|
0 | 239 | log.error(error) |
---|
0 | 240 | if self.onerror != 'ignore': |
---|
0 | 241 | raise BuildError("Build step '%s' failed" % self.id) |
---|
0 | 242 | log.warning("Continuing despite errors in step '%s'", self.id) |
---|
| 243 | |
---|
| 244 | |
---|
2 | 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. |
---|
1 | 250 | """ |
---|
| 251 | |
---|
1 | 252 | ERROR = 'error' |
---|
1 | 253 | LOG = 'log' |
---|
1 | 254 | REPORT = 'report' |
---|
1 | 255 | ATTACH = 'attach' |
---|
| 256 | |
---|
1 | 257 | def __init__(self, xml, basedir=os.getcwd(), 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 | """ |
---|
24 | 266 | assert isinstance(xml, xmlio.ParsedElement) |
---|
24 | 267 | vars = dict([(name, value) for name, value in xml.attr.items() |
---|
4 | 268 | if not name.startswith('xmlns')]) |
---|
24 | 269 | self.ctxt = Context(basedir, config, vars) |
---|
24 | 270 | self._root = xml |
---|
24 | 271 | self.onerror_default = vars.get('onerror', 'fail') |
---|
24 | 272 | assert self.onerror_default in ('fail', 'ignore', 'continue') |
---|
| 273 | |
---|
1 | 274 | def __iter__(self): |
---|
| 275 | """Iterate over the individual steps of the recipe.""" |
---|
40 | 276 | for child in self._root.children('step'): |
---|
22 | 277 | yield Step(child, self.onerror_default) |
---|
| 278 | |
---|
1 | 279 | def validate(self): |
---|
| 280 | """Validate the recipe. |
---|
| 281 | |
---|
| 282 | This method checks a number of constraints: |
---|
| 283 | - the name of the root element must be "build" |
---|
| 284 | - the only permitted child elements or the root element with the name |
---|
| 285 | "step" |
---|
| 286 | - the recipe must contain at least one step |
---|
| 287 | - step elements must have a unique "id" attribute |
---|
| 288 | - a step must contain at least one nested command |
---|
| 289 | - commands must not have nested content |
---|
| 290 | |
---|
| 291 | :raise InvalidRecipeError: in case any of the above contraints is |
---|
| 292 | violated |
---|
| 293 | """ |
---|
10 | 294 | if self._root.name != 'build': |
---|
1 | 295 | raise InvalidRecipeError('Root element must be <build>') |
---|
9 | 296 | steps = list(self._root.children()) |
---|
9 | 297 | if not steps: |
---|
1 | 298 | raise InvalidRecipeError('Recipe defines no build steps') |
---|
| 299 | |
---|
8 | 300 | step_ids = set() |
---|
11 | 301 | for step in steps: |
---|
10 | 302 | if step.name != 'step': |
---|
1 | 303 | raise InvalidRecipeError('Only <step> elements allowed at ' |
---|
1 | 304 | 'top level of recipe') |
---|
9 | 305 | if not step.attr.get('id'): |
---|
3 | 306 | raise InvalidRecipeError('Steps must have an "id" attribute') |
---|
| 307 | |
---|
6 | 308 | if step.attr['id'] in step_ids: |
---|
1 | 309 | raise InvalidRecipeError('Duplicate step ID "%s"' % |
---|
1 | 310 | step.attr['id']) |
---|
5 | 311 | step_ids.add(step.attr['id']) |
---|
| 312 | |
---|
5 | 313 | cmds = list(step.children()) |
---|
5 | 314 | if not cmds: |
---|
1 | 315 | raise InvalidRecipeError('Step "%s" has no recipe commands' % |
---|
1 | 316 | step.attr['id']) |
---|
7 | 317 | for cmd in cmds: |
---|
4 | 318 | if len(list(cmd.children())): |
---|
1 | 319 | raise InvalidRecipeError('Recipe command <%s> has nested ' |
---|
1 | 320 | 'content' % cmd.name) |
---|