|
45 | 45 | # other computer software, distribute, and sublicense such enhancements or
|
46 | 46 | # derivative works thereof, in binary and source code form.
|
47 | 47 |
|
| 48 | +import contextlib |
48 | 49 | import os
|
49 | 50 | import re
|
50 | 51 | import sys
|
@@ -377,6 +378,31 @@ def run(self):
|
377 | 378 | self.copy_file(src, dst, preserve_mode=False)
|
378 | 379 |
|
379 | 380 |
|
| 381 | +class Buck2EnvironmentFixer(contextlib.AbstractContextManager): |
| 382 | + """Removes HOME from the environment when running as root. |
| 383 | +
|
| 384 | + This script is sometimes run as root in docker containers. buck2 doesn't |
| 385 | + allow running as root unless $HOME is owned by root or is not set. |
| 386 | +
|
| 387 | + TODO(pytorch/test-infra#5091): Remove this once the CI jobs stop running as |
| 388 | + root. |
| 389 | + """ |
| 390 | + |
| 391 | + def __init__(self): |
| 392 | + self.saved_env = {} |
| 393 | + |
| 394 | + def __enter__(self): |
| 395 | + if os.geteuid() == 0 and "HOME" in os.environ: |
| 396 | + log.info("temporarily unsetting HOME while running as root") |
| 397 | + self.saved_env["HOME"] = os.environ.pop("HOME") |
| 398 | + return self |
| 399 | + |
| 400 | + def __exit__(self, *args, **kwargs): |
| 401 | + if "HOME" in self.saved_env: |
| 402 | + log.info("restored HOME") |
| 403 | + os.environ["HOME"] = self.saved_env["HOME"] |
| 404 | + |
| 405 | + |
380 | 406 | # TODO(dbort): For editable wheels, may need to update get_source_files(),
|
381 | 407 | # get_outputs(), and get_output_mapping() to satisfy
|
382 | 408 | # https://setuptools.pypa.io/en/latest/userguide/extension.html#setuptools.command.build.SubCommand.get_output_mapping
|
@@ -470,17 +496,13 @@ def run(self):
|
470 | 496 | if not self.dry_run:
|
471 | 497 | # Dry run should log the command but not actually run it.
|
472 | 498 | (Path(cmake_cache_dir) / "CMakeCache.txt").unlink(missing_ok=True)
|
473 |
| - try: |
474 |
| - # This script is sometimes run as root in docker containers. buck2 |
475 |
| - # doesn't allow running as root unless $HOME is owned by root or |
476 |
| - # does not exist. So temporarily undefine it while configuring |
477 |
| - # cmake, which runs buck2 to get some source lists. |
478 |
| - old_home = os.environ.pop("HOME", None) |
| 499 | + with Buck2EnvironmentFixer(): |
| 500 | + # The context manager may patch the environment while running this |
| 501 | + # cmake command, which happens to run buck2 to get some source |
| 502 | + # lists. |
| 503 | + |
479 | 504 | # Generate the build system files.
|
480 | 505 | self.spawn(["cmake", "-S", repo_root, "-B", cmake_cache_dir, *cmake_args])
|
481 |
| - finally: |
482 |
| - if old_home is not None: |
483 |
| - os.environ["HOME"] = old_home |
484 | 506 |
|
485 | 507 | # Build the system.
|
486 | 508 | self.spawn(["cmake", "--build", cmake_cache_dir, *build_args])
|
|
0 commit comments