blob: 33fc33fec0bbd6a94a96eba6e61555db367d9dbf [file] [edit]
import abc
import dataclasses
import enum
import logging
import os
import re
import subprocess
import time
from collections.abc import Sequence
from typing import Literal, Tuple, Type
import git
import github
logger = logging.getLogger(__name__)
def parse_targets(error_log: str | None) -> Sequence[str]:
if not error_log:
return []
return re.findall(r"\(from target (.*?)\)", error_log)
RetryExceptions = Tuple[Type[BaseException], ...]
def call_with_retry(exceptions : RetryExceptions, func, *args, **kwargs):
"""Calls a function and retries it if it raises specified exceptions.
Args:
exceptions: Tuple of exceptions to catch and retry on.
func: The callable to run.
*args: Positional arguments for func.
**kwargs: Keyword arguments for func.
"""
MAX_RETRIES = 3
DELAY = 3
BACKOFF = 2
val_delay = DELAY
func_name = getattr(func, "__name__", str(func))
if not exceptions:
raise ValueError("At least one exception class must be provided.")
for attempt in range(MAX_RETRIES):
try:
return func(*args, **kwargs)
except exceptions as e:
if attempt == MAX_RETRIES - 1:
logger.error(f"All {MAX_RETRIES} attempts to call {func_name} failed.")
raise
logger.warning(
f"Attempt {attempt + 1} to call {func_name} failed with {e}. "
f"Retrying in {val_delay} seconds..."
)
time.sleep(val_delay)
val_delay *= BACKOFF
@dataclasses.dataclass(frozen=True)
class BazelBuildConfig:
"""A Bazel invocation that CI runs and that the bot must keep passing."""
# Name of the configuration.
name: str
# Arguments (flags and targets) passed to the bazel-build scripts.
args: Tuple[str, ...]
# These must stay in sync with the Bazel invocations run by buildkite.
BAZEL_BUILD_CONFIGS: Tuple[BazelBuildConfig, ...] = (
BazelBuildConfig(
name="default",
args=(
"//...",
"@llvm-project//...",
),
),
BazelBuildConfig(
name="llvm_libc_fullbuild",
args=(
"--@llvm-project//libc:build_mode=full",
"@llvm-project//libc/...",
),
),
)
@dataclasses.dataclass(frozen=True, kw_only=True)
class BazelBuildSuccess:
"""A successful build result."""
success: Literal[True] = dataclasses.field(default=True, init=False)
@dataclasses.dataclass(frozen=True, kw_only=True)
class BazelBuildFailure:
"""The outputs of failed build result."""
success: Literal[False] = dataclasses.field(default=False, init=False)
stdout: str = ""
stderr: str = ""
config: BazelBuildConfig
# Result of a Bazel build. Check `result.success` to narrow the type.
BazelBuildResult = BazelBuildSuccess | BazelBuildFailure
class CredentialManager:
def __init__(self, use_github_app: bool):
self.gh_fork_user = os.getenv("GITHUB_FORK_USER")
self.gh_pr_user = os.getenv("GITHUB_PR_USER")
self.bk_token = os.getenv("BUILDKITE_API_TOKEN")
self.use_github_app = use_github_app
# GitHub app details
self.gh_app_id = os.getenv("GITHUB_APP_ID")
self.gh_app_private_key = os.getenv("GITHUB_APP_PRIVATE_KEY")
self.gh_pr_app_id = os.getenv("GITHUB_PR_APP_ID")
self.gh_pr_app_private_key = os.getenv("GITHUB_PR_APP_PRIVATE_KEY")
# Used when not using GitHub app
self.gh_fork_user_token = os.getenv("GITHUB_FORK_USER_TOKEN")
self.gh_pr_user_token = os.getenv("GITHUB_PR_USER_TOKEN")
if not self.use_github_app and not self.gh_fork_user_token:
raise EnvironmentError(
"GITHUB_FORK_USER_TOKEN must be set when not using GitHub app"
)
@property
def gh_fork_repo_name(self):
return f"{self.gh_fork_user}/llvm-project"
@property
def gh_pr_repo_name(self):
return f"{self.gh_pr_user}/llvm-project"
class CommandProcessor:
BazelPath = "utils/bazel"
def __init__(self, repo_path: str):
self.repo_path = repo_path
self.bazel_path = os.path.join(repo_path, self.BazelPath)
def bazel_build_in_kubernetes(self) -> bool:
return os.getenv("POD_NAME") is not None
def run_bazel_build(
self,
configs: Sequence[BazelBuildConfig] = BAZEL_BUILD_CONFIGS,
) -> BazelBuildResult:
"""Runs the bazel build for each of the given configurations.
Returns:
BazelBuildSuccess if every config built,
otherwise the BazelBuildFailure for the first config that failed.
"""
for config in configs:
result = self._run_bazel_build_with_config(config)
if not result.success:
# TODO: Consider building for every config and returning all
# failures. If there are distinct failures in multiple configs,
# the bant fixer probably won't succeed because it only makes
# one attempt at fixing the build based on this output.
return result
return BazelBuildSuccess()
def _run_bazel_build_with_config(
self,
config: BazelBuildConfig,
) -> BazelBuildResult:
"""Runs the bazel build for a single configuration."""
try:
bazel_build_file = (
"bazel-build-ci" if self.bazel_build_in_kubernetes() else "bazel-build"
)
base_path = os.path.dirname(os.path.abspath(__file__))
bazel_build_path = os.path.join(base_path, bazel_build_file)
env = os.environ.copy()
env["BAZEL_OUTPUT_BASE"] = f"/tmp/bazel_build_{config.name}"
logger.info(f"Running bazel build ({config.name})...")
start_time = time.time()
result = subprocess.run(
[bazel_build_path, *config.args],
cwd=os.path.join(self.repo_path, self.BazelPath),
env=env,
capture_output=True,
text=True,
timeout=1800, # 30 minutes
)
end_time = time.time()
time_taken = end_time - start_time
logger.info(f"Bazel build ({config.name}) took {time_taken} seconds.")
if result.returncode == 0:
return BazelBuildSuccess()
return BazelBuildFailure(
stdout=result.stdout,
stderr=result.stderr,
config=config,
)
except subprocess.TimeoutExpired:
return BazelBuildFailure(stderr="Timeout", config=config)
except FileNotFoundError:
return BazelBuildFailure(
stderr="Error: 'bazel' command not found. Please ensure Bazel is installed.",
config=config,
)
except Exception as e:
return BazelBuildFailure(
stderr=f"Error running bazel build: {str(e)}",
config=config,
)
def run_buildifier(self, files: Sequence[str]) -> bool:
"""
Runs buildifier on the given files.
Args:
repo_path: The absolute path to the root of the local git repository.
files: List of files to run buildifier on.
"""
if not files:
return False
cmd = ["buildifier"] + list(files)
logger.info(f"Running buildifier: {' '.join(cmd)}...")
result = subprocess.run(
cmd,
cwd=self.repo_path,
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0:
logger.error(f"Buildifier failed: {result.stderr}")
return False
return True
def run_bant(self, targets: Sequence[str]) -> bool:
"""
Runs bant on the given files.
Args:
repo_path: The absolute path to the root of the local git repository.
files: List of files to run bant on.
"""
try:
if not targets:
return False
# Target will be @@+_repo_rules+llvm-project//mlir:AMDGPUDialect
# We want @llvm-project//mlir:AMDGPUDialect
processed_targets = [
t.replace("@@+_repo_rules+llvm-project//", "@llvm-project//")
for t in targets
]
cmd = ["bant", "dwyu"] + processed_targets
logger.info(f"Running bant: {' '.join(cmd)}")
result = subprocess.run(
cmd,
cwd=os.path.join(self.repo_path, self.BazelPath),
capture_output=True,
text=True,
timeout=30,
)
for buildozer_cmd in result.stdout.splitlines():
logger.info(f"Executing: {buildozer_cmd}")
buildozer_cmd = buildozer_cmd.replace(
"@llvm-project//", "//llvm-project-overlay//"
)
buildozer_result = subprocess.run(
buildozer_cmd, shell=True, cwd=self.repo_path
)
if buildozer_result.returncode != 0:
logger.error(f"Buildozer command failed: {buildozer_cmd}")
return True
except Exception as e:
logger.error(f"Error running bant: {str(e)}")
return False
class LocalGitRepo:
def __init__(self, repo_path: str, creds: CredentialManager, can_create_pr):
self.can_create_pr = can_create_pr
self.repo_path = repo_path
self.creds = creds
if not os.path.exists(self.repo_path):
logger.info(
f"Cloning {self.creds.gh_fork_repo_name} to {self.repo_path}..."
)
git.Repo.clone_from(
f"https://github.com/{self.creds.gh_fork_repo_name}.git",
self.repo_path,
env={"GIT_DEFAULT_REF_FORMAT": "files"},
)
self.repo = git.Repo(repo_path)
if self.creds.use_github_app:
self.fork_github_integration = github.GithubIntegration(
auth=github.Auth.AppAuth(creds.gh_app_id, creds.gh_app_private_key)
)
self.gh_fork_installation = self.fork_github_integration.get_repo_installation(
self.creds.gh_fork_user, "llvm-project"
)
self.gh_fork_repo = (
self.gh_fork_installation.get_github_for_installation().get_repo(
self.creds.gh_fork_repo_name
)
)
self.pr_github_integration = github.GithubIntegration(
auth=github.Auth.AppAuth(creds.gh_pr_app_id, creds.gh_pr_app_private_key)
)
self.gh_pr_installation = self.pr_github_integration.get_repo_installation(
self.creds.gh_pr_user, "llvm-project"
)
self.gh_pr_repo = (
self.gh_pr_installation.get_github_for_installation().get_repo(
self.creds.gh_pr_repo_name
)
)
self.gh_pr_creator = f"{self.gh_pr_installation.app_slug}[bot]"
else:
self.gh_fork_repo = github.Github(self.creds.gh_fork_user_token).get_repo(self.creds.gh_fork_repo_name)
self.gh_pr_repo = github.Github(self.creds.gh_pr_user_token).get_repo(self.creds.gh_pr_repo_name) if self.can_create_pr else None
self.gh_pr_creator = self.creds.gh_pr_user
self.bazel_utils_path = os.path.join(self.repo_path, "utils", "bazel")
self.main_branch = "main"
self.remote_name = "origin"
self.author_name = os.getenv("GIT_AUTHOR_NAME", "Google Bazel Bot")
self.author_email = os.getenv("GIT_AUTHOR_EMAIL", "google-bazel-bot@google.com")
self.repo.git.update_environment(
GIT_AUTHOR_NAME=self.author_name,
GIT_AUTHOR_EMAIL=self.author_email,
GIT_COMMITTER_NAME=self.author_name,
GIT_COMMITTER_EMAIL=self.author_email,
)
self.branch_prefix = "bazel-"
def get_branch_name(self, commit_hash: str) -> str:
return f"{self.branch_prefix}{commit_hash}"
def refresh_main_branch(self) -> str:
"""Pulls the repository locally."""
call_with_retry(
(github.GithubException,),
self.gh_fork_repo.merge_upstream,
self.main_branch,
)
self.repo.git.checkout("-f", self.main_branch)
# Force pull by fetching and resetting to overwrite local changes.
call_with_retry(
(git.GitCommandError,),
self.repo.remotes.origin.fetch
)
self.repo.git.reset("--hard", f"{self.remote_name}/{self.main_branch}")
return self.repo.head.commit.hexsha
def diff(self) -> str:
return self.repo.git.diff(None)
def create_branch_for_fix(self, commit_hash: str) -> str:
"""Prepares the local git repository for applying fixes from current HEAD."""
branch_name = self.get_branch_name(commit_hash)
self.repo.create_head(branch_name, force=True).checkout()
return branch_name
def rebase_branch(
self, branch_name: str, new_base: str, strategy_option: str = "ours"
) -> bool:
"""Rebases branch_name onto new_base. Returns True on success, False on conflict/error."""
try:
self.repo.git.checkout("-f", branch_name)
self.repo.git.clean("-fd")
self.repo.git.rebase("-X", strategy_option, new_base)
return True
except git.GitCommandError as e:
logger.error(f"Failed to rebase {branch_name} onto {new_base}: {e}")
try:
self.repo.git.rebase("--abort")
except git.GitCommandError:
pass
return False
def reset_hard(self, commit_or_branch: str | None = None) -> None:
"""Hard resets the repository and cleans untracked files."""
if commit_or_branch:
self.repo.git.reset("--hard", commit_or_branch)
else:
self.repo.git.reset("--hard")
self.repo.git.clean("-fd")
def checkout_commit(self, commit_hash: str):
"""Prepares the local git repository for applying fixes."""
self.refresh_main_branch()
self.repo.git.checkout("-f", commit_hash)
def commit(self, message: str) -> None:
self.repo.git.add(".")
actor = git.Actor(self.author_name, self.author_email)
self.repo.index.commit(message, author=actor, committer=actor)
def is_repo_dirty(self, untracked_files=False) -> bool:
return self.repo.is_dirty(untracked_files=untracked_files)
def close_existing_prs(self) -> None:
for open_pr in self.gh_pr_repo.get_issues(
creator=self.gh_pr_creator, state="open"
):
print(f"Closing unmerged PR from previous fix attempt: {open_pr.url}")
open_pr.edit(state="closed")
def push_fix(
self,
build_data: "BuildInfo",
create_pr: bool | None = None,
close_existing_prs: bool = True,
) -> bool:
"""Pushes the branch and creates a GitHub PR against it."""
if create_pr is None:
create_pr = self.can_create_pr
commit_hash = build_data.commit
branch_name = self.get_branch_name(commit_hash)
# 1. Get access token
try:
access_token = (
call_with_retry(
(github.GithubException,),
self.fork_github_integration.get_access_token,
self.gh_fork_installation.id,
).token
if self.creds.use_github_app
else self.creds.gh_fork_user_token
)
except github.GithubException as e:
logger.error(f"Failed to get access token: {e}")
return False
# 2. Setup Remote and Push
try:
self.repo.delete_remote(self.remote_name)
except git.GitCommandError as e:
logger.debug(f"Failed to delete remote (might not exist): {e}")
self.repo.create_remote(
self.remote_name,
f"https://x-access-token:{access_token}@github.com/{self.creds.gh_fork_repo_name}.git",
)
logger.debug(f"New remote {self.remote_name} created.")
# 3. Push fixes to the branch
try:
call_with_retry(
(git.GitCommandError,),
self.repo.git.push,
"--set-upstream",
self.remote_name,
f"HEAD:{branch_name}",
"-f",
)
except git.GitCommandError as e:
logger.error(f"All attempts to push branch {branch_name} failed: {e}")
return False
if not create_pr:
logger.info("PR creation disabled. Skipping PR creation.")
logger.info(
f"Pull request can be created at: https://github.com/llvm/llvm-project/compare/main...{self.creds.gh_fork_user}:llvm-project:{branch_name}?expand=1"
)
return True
# 4. Close existing PRs (if any)
if close_existing_prs:
try:
call_with_retry(
(github.GithubException,),
self.close_existing_prs,
)
except github.GithubException as e:
logger.warning(f"Failed to close existing PRs: {e}. Proceeding anyway.")
# 5. Create new Pull Request
logger.info(
f"Creating Pull Request for branch {branch_name} from {self.creds.gh_fork_repo_name} to {self.creds.gh_pr_repo_name}..."
)
buildkite_url = build_data.buildkite_url
pr_number_suffix = f" (#{build_data.pr_number})" if build_data.pr_number else ""
pr_body = (
f"This fixes {commit_hash}{pr_number_suffix}.\n\n"
f"Buildkite error link: {buildkite_url}\n"
)
try:
if not self.creds.use_github_app:
if create_pr and not self.creds.gh_pr_user_token:
raise EnvironmentError(
"GITHUB_PR_USER_TOKEN must be set to create PR when not using GitHub App."
)
pr = call_with_retry(
(github.GithubException,),
self.gh_pr_repo.create_pull,
title=f"[Bazel] Fixes {commit_hash[:7]}",
body=pr_body,
head=f"{self.creds.gh_fork_user}:{branch_name}",
base=self.main_branch,
maintainer_can_modify=False,
)
logger.info(f"Pull Request Created: {pr.html_url}")
return True
except github.GithubException as e:
logger.error(f"All attempts to create PR failed: {e}")
return False
class BuildState(enum.Enum):
UNKNOWN = "unknown"
PASSED = "passed"
FAILED = "failed"
RUNNING = "running"
SCHEDULED = "scheduled"
@dataclasses.dataclass
class BuildInfo:
commit: str
state: BuildState = BuildState.UNKNOWN
failed_targets: Sequence[str] = dataclasses.field(default_factory=list)
build_number: int | None = None
pr_number: int | None = None
@property
def buildkite_url(self) -> str:
if self.build_number is not None:
return f"https://buildkite.com/llvm-project/upstream-bazel/builds/{self.build_number}"
return f"https://buildkite.com/llvm-project/upstream-bazel/builds?commit={self.commit}"
class BuildProcessor(abc.ABC):
@abc.abstractmethod
def get_latest_build_status(self) -> BuildInfo | None:
"""Get the latest build status."""
pass
@abc.abstractmethod
def get_builds_to_process(self, last_processed_sha: str) -> Sequence[BuildInfo]:
"""Get builds to process since last processed build."""
pass
class LocalBuildProcessor(BuildProcessor):
def __init__(self, cmd_processor: CommandProcessor, git_repo: LocalGitRepo):
self.cmd_processor = cmd_processor
self.git_repo = git_repo
def get_latest_build_status(self) -> BuildInfo:
"""Get the latest build status by running bazel build locally."""
latest_sha = self.git_repo.refresh_main_branch()
result = self.cmd_processor.run_bazel_build()
if result.success:
return BuildInfo(commit=latest_sha, state=BuildState.PASSED)
return BuildInfo(
commit=latest_sha,
state=BuildState.FAILED,
failed_targets=parse_targets(result.stderr),
)
def get_builds_to_process(self, last_processed_sha: str) -> Sequence[BuildInfo]:
"""Get builds to process since last processed build by checking commits since then."""
self.git_repo.refresh_main_branch()
repo = self.git_repo.repo
# First ensure that last_processed_sha is in the main branch
try:
if not repo.is_ancestor(
repo.commit(last_processed_sha), repo.commit(self.git_repo.main_branch)
):
logger.error(
f"Commit {last_processed_sha} is not in branch {self.git_repo.main_branch}"
)
return []
except Exception as e:
logger.error(
f"Commit {last_processed_sha} not found or error checking ancestry: {e}"
)
return []
commits = list(
repo.iter_commits(f"{last_processed_sha}..{self.git_repo.main_branch}")
)
builds = []
for commit in commits:
title = commit.message.splitlines()[0].strip() if getattr(commit, "message", None) else ""
match = re.search(r"\(#(\d+)\)$", title)
pr_number = int(match.group(1)) if match else None
builds.append(
BuildInfo(
commit=commit.hexsha,
state=BuildState.UNKNOWN,
failed_targets=[],
pr_number=pr_number,
)
)
builds.reverse() # Oldest first
return builds