Debian Codegraph @

.ci/buildbot/worker.py

raw
1 # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
2 # See https://llvm.org/LICENSE.txt for license information.
3 # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4 """Utilities for ScriptedBuilder Buildbot worker scripts"""
5
6 import argparse
7 import filecmp
8 import os
9 import stat
10 import pathlib
11 import re
12 import shlex
13 import shutil
14 import subprocess
15 import sys
16 import traceback
17 import platform
18 import multiprocessing
19 from contextlib import contextmanager
20
21 _SHQUOTE_WINDOWS_ESCAPEDCHARS = re.compile(r'(["\\])')
22 _SHQUOTE_WINDOWS_QUOTEDCHARS = re.compile("[ \t\n]")
23
24
25 def _shquote_windows(txt):
26 """shlex.quote for Windows cmd.exe"""
27 txt = txt.replace("%", "%%")
28 quoted = re.sub(_SHQUOTE_WINDOWS_ESCAPEDCHARS, r"\\\1", txt)
29 if len(quoted) == len(txt) and not _SHQUOTE_WINDOWS_QUOTEDCHARS.search(txt):
30 return txt
31 else:
32 return '"' + quoted + '"'
33
34
35 def shjoin(args):
36 """Convert a list of shell arguments to an appropriately quoted string."""
37 if os.name in set(("nt", "os2", "ce")):
38 return " ".join(map(_shquote_windows, args))
39 else:
40 return shlex.join(args)
41
42
43 def report(msg):
44 """
45 Emit a message to the build log. Appears in red font. Lines surrounded
46 by @@@ may be interpreted as meta-instructions.
47 """
48 print(msg, file=sys.stderr, flush=True)
49
50
51 def report_prog_version(name, cmd):
52 try:
53 p = subprocess.run(cmd, check=True, capture_output=True, text=True)
54 outlines = p.stdout.strip().splitlines()
55 report_list(name, outlines[0])
56 except BaseException:
57 pass
58
59
60 def report_list(category, *items):
61 items = list(items)
62 filtered = []
63
64 while items:
65 item = items.pop()
66 match item:
67 case tuple() | list():
68 items += item
69 continue
70 case None:
71 continue
72 case _:
73 item = str(item).strip()
74 if not item:
75 continue
76 if item in filtered:
77 continue
78 filtered.append(item)
79 category += ":"
80 report(f"{category:<9}{', '.join(reversed( filtered))}")
81
82
83 def report_platform():
84 report_list(
85 "CPU",
86 platform.machine(),
87 platform.architecture()[0],
88 platform.processor(),
89 f"{multiprocessing.cpu_count()} native threads",
90 )
91 try:
92 releaseinfo = platform.freedesktop_os_release()
93 except BaseException:
94 releaseinfo = dict()
95 report_list(
96 "OS",
97 platform.system(),
98 platform.architecture()[1],
99 platform.platform(),
100 releaseinfo.get("PRETTY_NAME"),
101 )
102 report_list("Python", platform.python_implementation(), platform.python_version())
103
104 report_prog_version("CMake", ["cmake", "--version"])
105 report_prog_version("Ninja", ["ninja", "--version"])
106 report_prog_version("Sphinx", ["sphinx-build", "--version"])
107 report_prog_version("Doxygen", ["doxygen", "--version"])
108
109 report_prog_version("gcc", ["gcc", "--version"])
110 report_prog_version("ld", ["ld", "--version"])
111
112 report_prog_version("LLVM", ["llvm-config", "--version"])
113 report_prog_version("Clang", ["clang", "--version"])
114 report_prog_version("LLD", ["ld.lld", "--version"])
115
116
117 def run_command(cmd, shell=False, **kwargs):
118 """
119 Report which command is being run, then execute it using
120 subprocess.check_call.
121 """
122 report(f"Running: {cmd if shell else shjoin(cmd)}")
123 sys.stderr.flush()
124 subprocess.check_call(cmd, shell=shell, **kwargs)
125
126
127 def _remove_readonly(func, path, _):
128 """Clear the readonly bit and reattempt the removal."""
129 try:
130 os.chmod(path, stat.S_IWRITE)
131 except Exception:
132 pass
133 func(path)
134
135
136 def rmtree(path):
137 """Remove directory path and all its subdirectories. Includes a workaround
138 for Windows where shutil.rmtree errors on read-only files.
139
140 Taken from official Python docs
141 https://docs.python.org/3/library/shutil.html#rmtree-example
142 """
143 shutil.rmtree(path, onexc=_remove_readonly)
144
145
146 def try_delete(path):
147 """
148 Delete the file or directory;
149 if not successful, print a warning but continue
150 """
151 try:
152 os.unlink(path)
153 except Exception:
154 try:
155 _remove_readonly(os.unlink, path, _)
156 except Exception:
157 try:
158 rmtree(path)
159 except Exception as e:
160 print(f"Warning: Could not delete {path}: {e}")
161
162
163 def checkout(giturl, sourcepath):
164 """
165 Use git to checkout the remote repository giturl at local directory
166 sourcepath.
167
168 If the repository already exists, clear all local changes and check out the
169 latest main branch.
170 """
171 if not os.path.exists(sourcepath):
172 run_command(["git", "clone", giturl, sourcepath])
173
174 # Reset repository state no matter what there was before
175 run_command(["git", "-C", sourcepath, "stash", "--all"])
176 run_command(["git", "-C", sourcepath, "stash", "clear"])
177
178 # Fetch and checkout the newest
179 run_command(["git", "-C", sourcepath, "fetch", "origin"])
180 run_command(["git", "-C", sourcepath, "checkout", "origin/main", "--detach"])
181
182
183 @contextmanager
184 def step(step_name, halt_on_fail=False):
185 """Report a new build step being started.
186
187 Use like this::
188 with step("greet-step"):
189 report("Hello World!")
190 """
191 # Barrier to separate stdio output for the the previous step
192 sys.stderr.flush()
193 sys.stdout.flush()
194
195 report(f"@@@BUILD_STEP {step_name}@@@")
196 if halt_on_fail:
197 report("@@@HALT_ON_FAILURE@@@")
198 try:
199 yield
200 except Exception as e:
201 if isinstance(e, subprocess.CalledProcessError):
202 report(f"{shjoin(e.cmd)} exited with return code {e.returncode}.")
203 report("@@@STEP_FAILURE@@@")
204 else:
205 traceback.print_exc()
206 report("@@@STEP_EXCEPTION@@@")
207 if halt_on_fail:
208 # Do not continue with the next steps, but allow except/finally
209 # blocks to execute
210 raise e
211
212
213 class Worker:
214 """Helper class to keep context in a worker.run() environment"""
215
216 def __init__(self, args, clean, clobber, workdir, jobs, cachefile, llvmsrcroot):
217 self.args = args
218 self.clean = clean
219 self.clobber = clobber
220 self.workdir = workdir
221 self.jobs = jobs
222 self.cachefile = cachefile
223 self.llvmsrcroot = llvmsrcroot
224
225 def in_llvmsrc(self, path):
226 """
227 Convert a path in the llvm-project source checkout to an absolute path
228 """
229 return os.path.join(self.llvmsrcroot, path)
230
231 def in_workdir(self, path):
232 """Convert a path in the workdir to an absolute path"""
233 return os.path.join(self.workdir, path)
234
235 def run_ninja(
236 self, targets: list = [], *, builddir, ccache_stats: bool = False, **kwargs
237 ):
238 """
239 Run ninja in builddir. If self.jobs is set, automatically adds a
240 -j option to set the number of parallel jobs.
241
242 Parameters
243 ----------
244 targets : list
245 List of build targets; build the default target 'all' if list is
246 empty
247 builddir
248 Directory of the build.ninja file
249 ccache_stats : bool
250 If true, also emit ccache statistics when finishing the build
251 """
252 cmd = ["ninja"]
253 if builddir is not None:
254 cmd += ["-C", builddir]
255 cmd += targets
256 if self.jobs:
257 cmd.append(f"-j{self.jobs}")
258 if ccache_stats:
259 run_command(["ccache", "-z"])
260 try:
261 run_command(cmd, **kwargs)
262 finally:
263 # TODO: Pipe to stderr to separate from build log itself
264 run_command(["ccache", "-sv"])
265 else:
266 run_command(cmd, **kwargs)
267
268 @contextmanager
269 def step(self, step_name, halt_on_fail=False):
270 """Convenience wrapper for step()"""
271 with step(step_name, halt_on_fail=halt_on_fail) as s:
272 yield s
273
274 def report(self, msg):
275 """Convenience wrapper for report()"""
276 report(msg)
277
278 def run_command(self, *args, **kwargs):
279 """Convenience wrapper for run_command()"""
280 return run_command(*args, **kwargs)
281
282 def rmtree(self, *args, **kwargs):
283 """Convenience wrapper for rmtree()"""
284 return rmtree(*args, *kwargs)
285
286 def checkout(self, giturl, sourcepath):
287 """Convenience wrapper for checkout()"""
288 return checkout(giturl, sourcepath)
289
290
291 def convert_bool(v):
292 """Convert input to bool type
293
294 Use to convert the value of bool environment variables. Specifically, the
295 buildbot master sets 'false' to build properties, which by default Python
296 would interpret as true-ish.
297 """
298 match v:
299 case None:
300 return False
301 case bool(b):
302 return b
303 case str(s):
304 return not s.strip().upper() in ["", "0", "N", "NO", "FALSE", "OFF"]
305 case _:
306 return bool(v)
307
308
309 def relative_if_possible(path, relative_to):
310 """
311 Like os.path.relpath, but does not fail if path is not a parent of
312 relative_to; keeps the original path in that case
313 """
314 path = os.path.normpath(path)
315 if not os.path.isabs(path):
316 # Path is already relative (assumed to relative_to)
317 return path
318 try:
319 result = os.path.relpath(path, start=relative_to)
320 return result if result else path
321 except ValueError:
322 return path
323
324
325 @contextmanager
326 def run(
327 scriptpath,
328 llvmsrcroot,
329 parser=None,
330 cachefile=None,
331 clobberpaths=[],
332 workerjobs=None,
333 incremental=None,
334 ):
335 """
336 Runs the boilerplate for a ScriptedBuilder buildbot. It is not necessary to
337 use this function (one can also call run_command() etc. directly), but
338 allows for some more flexibility and safety checks. Arguments passed to this
339 function represent the worker configuration.
340
341 We use the term 'clean' for resetting the worker to an empty state. This
342 involves deleting ${prefix}/llvm.src as well as ${prefix}/build.
343 The term 'clobber' means deleting build artifacts, but not already
344 downloaded git repositories. Build artifacts include build- and
345 install-directories. Changes in the llvm.src directory will
346 either be force-reset by the buildbot's 'checkout' step anyway,
347 or -- in case of local invocation -- represents the source the user wants
348 to reproduce without being tied to a specific commit. In either case the
349 source directories should not be touched. We consider 'clean' to comprise
350 'clobber'. llvm-zorg also uses the term 'clean_obj' instead of 'clobber'.
351 By default, we will always clobber to get the same starting point at every
352 build. If incremental=True or the --incremental command line option is used,
353 the starting point is the previous build.
354
355 A buildbot worker will invoke this script using this directory structure,
356 where ${prefix} is a dedicated directory for this builder:
357 ${prefix}/llvm.src # Checkout location for the llvm-source
358 ${prefix}/build # cwd when launching the build script
359
360 The build script is called with --workdir=. parameter, i.e. the build
361 artifacts are written into ${prefix}/build. When cleaning, the worker (NOT
362 the build script) will delete ${prefix}/llvm.src; Deleting any contents of
363 ${prefix}/build is to be done by the builder script, e.g. by this function.
364 The builder script can choose to not delete the complete workdir, e.g.
365 additional source checkouts such as the llvm-test-suite.
366
367 The buildbot master will set the 'clean' build property and the environment
368 variable BUILDBOT_CLEAN when in the GUI the option "Clean source code and
369 build directory" is checked by the user. The 'clean_obj' build property and
370 the BUILDBOT_CLEAN_OBJ environment variable will be set when either the
371 "Clean build directory" GUI option is set, or the master detects a change
372 to a CMakeLists.txt or *.cmake file.
373
374 Parameters
375 ----------
376 scriptpath
377 Pass __file__ from the main builder script.
378 llvmsrcroot
379 Absolute path to the llvm-project source checkout. Since the builder
380 script is supposed to be a part of llvm-project itself, the builder
381 script can compute it from __file__.
382 parser
383 Use this argparse.ArgumentParser instead of creating a new one. Allows
384 adding additional command line switches in addition to the pre-defined
385 ones. Build scripts are encouraged to apply the pre-defined switches.
386 cachefile
387 Path (relative to llvmsrcroot) of the CMake cache file to
388 use. `None` indicates that the script does not use a cache file. Can be
389 overridden using --cachefile.
390 clobberpaths
391 Directories relative to workdir that need to be deleted if the build
392 configuration changes (due to changes of CMakeLists.txt or changes of
393 configuration parameters). Typically, only source checkouts are not
394 deleted.
395 workerjobs
396 Default number of build and test jobs; If set, expected to be the number
397 of jobs of the actual buildbot worker that executes this script. Can be
398 overridden using the --jobs parameter so in case someone needs to
399 reproduce this build, they can adjust the number of jobs for the
400 reproducer platform. Alternatively, the worker can set the
401 BUILDBOT_JOBS environment variable or keep ninja/llvm-lit defaults.
402 incremental
403 Only clobber the build artifacts when the build configuration changes.
404 Can be overridden using --incremental.
405 """
406
407 scriptpath = os.path.abspath(scriptpath)
408 llvmsrcroot = os.path.abspath(llvmsrcroot)
409 stem = pathlib.Path(scriptpath).stem
410 workdir_default = f"{stem}.workdir"
411
412 jobs_default = None
413 if jobs_env := os.environ.get("BUILDBOT_JOBS"):
414 jobs_default = int(jobs_env)
415 if not jobs_default:
416 jobs_default = workerjobs
417 if not jobs_default:
418 jobs_default = None
419
420 incremental_default = None if incremental else False
421
422 parser = parser or argparse.ArgumentParser(
423 allow_abbrev=True,
424 description="When executed without arguments, builds the worker's "
425 f"LLVM build configuration in {os.path.abspath(workdir_default)}. "
426 "Some build configuration parameters can be altered using the "
427 "following switches:",
428 )
429 parser.add_argument(
430 "--workdir",
431 default=workdir_default,
432 help="Use this dir (relative to cwd) as workdir to write the build "
433 "artifacts into; --workdir=. uses the current directory.\nWarning: The "
434 "content of this directory may be deleted",
435 )
436 if cachefile is not None:
437 parser.add_argument(
438 "--cachefile",
439 default=relative_if_possible(cachefile, llvmsrcroot),
440 help="File containing the initial values for the CMakeCache.txt "
441 "for the llvm build.",
442 )
443 parser.add_argument(
444 "--clean",
445 action=argparse.BooleanOptionalAction,
446 default=convert_bool(os.environ.get("BUILDBOT_CLEAN")),
447 help="Delete the entire workdir before starting the build, including "
448 "source directories",
449 )
450 parser.add_argument(
451 "--incremental",
452 action=argparse.BooleanOptionalAction,
453 default=incremental_default,
454 help="Keep previous build artifacts when starting the build",
455 )
456 parser.add_argument(
457 "--jobs",
458 "-j",
459 type=int,
460 default=jobs_default,
461 help="Number of build- and test-jobs",
462 )
463 args = parser.parse_args()
464
465 workdir = os.path.abspath(args.workdir)
466 incremental = args.incremental
467 clean = args.clean
468 if cachefile is not None:
469 cachefile = os.path.join(llvmsrcroot, args.cachefile)
470 if not os.path.isfile(cachefile):
471 raise Exception(f"--cachefile={cachefile} does not exist")
472
473 prevcachepath = os.path.join(workdir, "prevcache.cmake")
474 prevscriptpath = os.path.join(workdir, "prevscript.py")
475
476 if clean:
477 # Clean implies clobber
478 clobber = False
479 elif incremental is None:
480 # Automatically determine whether to clobber
481 def has_config_change():
482 # Has the master scheduler determined a CMakeLists.txt has changed?
483 if convert_bool(os.environ.get("BUILDBOT_CLOBBER")):
484 return True
485 if convert_bool(os.environ.get("BUILDBOT_CLEAN_OBJ")):
486 return True
487
488 # Has the build script changed?
489 if not os.path.isfile(prevscriptpath):
490 return True
491 if not filecmp.cmp(scriptpath, prevscriptpath, shallow=False):
492 return True
493
494 # Has the cache file (if any) changed?
495 if cachefile:
496 if not os.path.isfile(prevcachepath):
497 return True
498 if not os.path.isfile(cachefile):
499 return True
500 if not filecmp.cmp(cachefile, prevcachepath, shallow=False):
501 return True
502
503 return False
504
505 clobber = has_config_change()
506 else:
507 # Adhere to explicitly set incremental option
508 clobber = not incremental
509
510 # Safety check
511 parentdir = os.path.dirname(scriptpath)
512 while True:
513 if os.path.exists(workdir) and os.path.samefile(parentdir, workdir):
514 raise Exception(
515 f"Cannot use {args.workdir} as workdir; it contains the source "
516 "itself in '{parentdir}'"
517 )
518 newparentdir = os.path.dirname(parentdir)
519 if newparentdir == parentdir:
520 break
521 parentdir = newparentdir
522
523 w = Worker(
524 args,
525 clean=clean,
526 clobber=clobber,
527 workdir=workdir,
528 jobs=args.jobs,
529 cachefile=cachefile,
530 llvmsrcroot=llvmsrcroot,
531 )
532
533 with step("platform-info"):
534 report_platform()
535
536 # Ensure that the cwd is not the directory we are going to delete. This
537 # would not work e.g. under Windows. We will chdir to workdir in the next
538 # step anyway.
539 os.chdir("/")
540
541 if clean:
542 if os.path.exists(workdir):
543 print("Deleting previous build state including sources", file=sys.stderr)
544
545 with w.step(f"clean"):
546 if os.path.exists(workdir):
547 # Do not delete the directory itself, just the contents; it might be
548 # a symlink to somewhere else
549 for d in os.listdir(workdir):
550 try_delete(os.path.join(workdir, d))
551 elif clobber:
552 # Warn user if deleting anything
553 for p in clobberpaths:
554 if os.path.exists(os.path.join(workdir, p)):
555 print(
556 "Deleting previous build artifacts; use --incremental to keep",
557 file=sys.stderr,
558 )
559 break
560
561 with w.step(f"clobber"):
562 for d in clobberpaths:
563 try_delete(os.path.join(workdir, d))
564 try_delete(prevscriptpath)
565 try_delete(prevcachepath)
566
567 os.makedirs(workdir, exist_ok=True)
568 os.chdir(workdir)
569
570 # Remember used script and cachefile to detect changes
571 shutil.copy(scriptpath, prevscriptpath)
572 if cachefile:
573 shutil.copy(cachefile, prevcachepath)
574
575 os.environ["NINJA_STATUS"] = "[%p/%es :: %u->%r->%f (of %t)] "
576
577 yield w