|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +import sys |
| 4 | +import traceback |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +from pydantic import BaseModel, Field |
| 8 | + |
| 9 | +from beeai_framework.agents.experimental.requirements.conditional import ( |
| 10 | + ConditionalRequirement, |
| 11 | +) |
| 12 | +from beeai_framework.backend import ChatModel |
| 13 | +from beeai_framework.errors import FrameworkError |
| 14 | +from beeai_framework.memory import UnconstrainedMemory |
| 15 | +from beeai_framework.middleware.trajectory import GlobalTrajectoryMiddleware |
| 16 | +from beeai_framework.tools import Tool |
| 17 | +from beeai_framework.tools.search.duckduckgo import DuckDuckGoSearchTool |
| 18 | +from beeai_framework.tools.think import ThinkTool |
| 19 | + |
| 20 | +from base_agent import BaseAgent, TInputSchema, TOutputSchema |
| 21 | +from observability import setup_observability |
| 22 | +from tools import ShellCommandTool |
| 23 | +from triage_agent import BackportData, ErrorData |
| 24 | +from utils import redis_client |
| 25 | + |
| 26 | + |
| 27 | +class InputSchema(BaseModel): |
| 28 | + package: str = Field(description="Package to update") |
| 29 | + upstream_fix: str = Field(description="Link to an upstream fix for the issue") |
| 30 | + jira_issue: str = Field(description="Jira issue to reference as resolved") |
| 31 | + dist_git_branch: str = Field(description="Git branch in dist-git to be updated") |
| 32 | + gitlab_user: str = Field( |
| 33 | + description="Name of the GitLab user", |
| 34 | + default=os.getenv("GITLAB_USER", "rhel-packaging-agent"), |
| 35 | + ) |
| 36 | + git_url: str = Field( |
| 37 | + description="URL of the git repository", |
| 38 | + default="https://gitlab.com/redhat/centos-stream/rpms", |
| 39 | + ) |
| 40 | + git_user: str = Field(description="Name of the git user", default="RHEL Packaging Agent") |
| 41 | + git_email: str = Field( |
| 42 | + description="E-mail address of the git user", default="[email protected]" |
| 43 | + ) |
| 44 | + |
| 45 | + |
| 46 | +class OutputSchema(BaseModel): |
| 47 | + success: bool = Field(description="Whether the backport was successfully completed") |
| 48 | + status: str = Field(description="Backport status") |
| 49 | + mr_url: Optional[str] = Field(description="URL to the opened merge request") |
| 50 | + error: Optional[str] = Field(description="Specific details about an error") |
| 51 | + |
| 52 | + |
| 53 | +class BackportAgent(BaseAgent): |
| 54 | + def __init__(self) -> None: |
| 55 | + super().__init__( |
| 56 | + llm=ChatModel.from_name(os.getenv("CHAT_MODEL")), |
| 57 | + tools=[ThinkTool(), ShellCommandTool(), DuckDuckGoSearchTool()], |
| 58 | + memory=UnconstrainedMemory(), |
| 59 | + requirements=[ |
| 60 | + ConditionalRequirement(ThinkTool, force_after=Tool, consecutive_allowed=False), |
| 61 | + ], |
| 62 | + middlewares=[GlobalTrajectoryMiddleware()], |
| 63 | + ) |
| 64 | + |
| 65 | + @property |
| 66 | + def input_schema(self) -> type[TInputSchema]: |
| 67 | + return InputSchema |
| 68 | + |
| 69 | + @property |
| 70 | + def output_schema(self) -> type[TOutputSchema]: |
| 71 | + return OutputSchema |
| 72 | + |
| 73 | + @property |
| 74 | + def prompt(self) -> str: |
| 75 | + return """ |
| 76 | + You are an agent for backporting a fix for a CentOS Stream package. You will prepare the content |
| 77 | + of the update and then create a commit with the changes. Create a temporary directory and always work |
| 78 | + inside it. Follow exactly these steps: |
| 79 | +
|
| 80 | + 1. Find the location of the {{ package }} package at {{ git_url }}. Always use the {{ dist_git_branch }} branch. |
| 81 | +
|
| 82 | + 2. Check if the package {{ package }} already has the fix {{ jira_issue }} applied. |
| 83 | +
|
| 84 | + 3. Create a local Git repository by following these steps: |
| 85 | + * Check if the fork already exists for {{ gitlab_user }} as {{ gitlab_user }}/{{ package }} and if not, |
| 86 | + create a fork of the {{ package }} package using the glab tool. |
| 87 | + * Clone the fork using git and HTTPS into the temp directory. |
| 88 | + * Run command `centpkg sources` in the cloned repository which downloads all sources defined in the RPM specfile. |
| 89 | + * Create a new Git branch named `automated-package-update-{{ jira_issue }}`. |
| 90 | +
|
| 91 | + 4. Update the {{ package }} with the fix: |
| 92 | + * Updating the 'Release' field in the .spec file as needed (or corresponding macros), following packaging |
| 93 | + documentation. |
| 94 | + * Make sure the format of the .spec file remains the same. |
| 95 | + * Fetch the upstream fix {{ upstream_fix }} locally and store it in the git repo as "{{ jira_issue }}.patch". |
| 96 | + * Add a new "Patch:" entry in the spec file for patch "{{ jira_issue }}.patch". |
| 97 | + * Verify that the patch is being applied in the "%prep" section. |
| 98 | + * Creating a changelog entry, referencing the Jira issue as "Resolves: <jira_issue>" for the issue {{ jira_issue }}. |
| 99 | + The changelog entry has to use the current date. |
| 100 | + * IMPORTANT: Only performing changes relevant to the backport update: Do not rename variables, |
| 101 | + comment out existing lines, or alter if-else branches in the .spec file. |
| 102 | +
|
| 103 | + 5. Verify and adjust the changes: |
| 104 | + * Use `rpmlint` to validate your .spec file changes and fix any new errors it identifies. |
| 105 | + * Generate the SRPM using `rpmbuild -bs` (ensure your .spec file and source files are correctly copied |
| 106 | + to the build environment as required by the command). |
| 107 | + * Verify the newly added patch applies cleanly using the command `centpkg prep`. |
| 108 | +
|
| 109 | + 6. Commit the changes: |
| 110 | + * The title of the Git commit should be in the format "[DO NOT MERGE: AI EXPERIMENTS] backport {{ jira_issue }}" |
| 111 | + * Include the reference to Jira as "Resolves: <jira_issue>" for the issue {{ jira_issue }}. |
| 112 | + * Commit the RPM spec file change and the newly added patch file. |
| 113 | + * Push the commit to the fork. |
| 114 | +
|
| 115 | + 7. Open a merge request: |
| 116 | + * Authenticate using `glab` |
| 117 | + * Open a merge request against the upstream repository of the {{ package }} in {{ git_url }} |
| 118 | + with previously created commit. |
| 119 | + """ |
| 120 | + |
| 121 | + |
| 122 | +async def main() -> None: |
| 123 | + setup_observability(os.getenv("COLLECTOR_ENDPOINT")) |
| 124 | + agent = BackportAgent() |
| 125 | + |
| 126 | + if ( |
| 127 | + (package := os.getenv("PACKAGE", None)) |
| 128 | + and (upstream_fix := os.getenv("UPSTREAM_FIX", None)) |
| 129 | + and (jira_issue := os.getenv("JIRA_ISSUE", None)) |
| 130 | + and (branch := os.getenv("BRANCH", None)) |
| 131 | + ): |
| 132 | + input = InputSchema( |
| 133 | + package=package, |
| 134 | + upstream_fix=upstream_fix, |
| 135 | + jira_issue=jira_issue, |
| 136 | + dist_git_branch=branch, |
| 137 | + ) |
| 138 | + output = await agent.run_with_schema(input) |
| 139 | + print(output.model_dump_json(indent=4)) |
| 140 | + return |
| 141 | + |
| 142 | + class Task(BaseModel): |
| 143 | + metadata: dict = Field(description="Task metadata") |
| 144 | + attempts: int = Field(default=0, description="Number of processing attempts") |
| 145 | + |
| 146 | + async with redis_client(os.getenv("REDIS_URL")) as redis: |
| 147 | + max_retries = int(os.getenv("MAX_RETRIES", 3)) |
| 148 | + while True: |
| 149 | + element = await redis.brpop("backport_queue", timeout=30) |
| 150 | + if element is None: |
| 151 | + continue |
| 152 | + _, payload = element |
| 153 | + task = Task.model_validate_json(payload) |
| 154 | + backport_data = BackportData.model_validate(task.metadata) |
| 155 | + input = InputSchema( |
| 156 | + package=backport_data.package, |
| 157 | + upstream_fix=backport_data.patch_url, |
| 158 | + jira_issue=backport_data.jira_issue, |
| 159 | + dist_git_branch=backport_data.branch, |
| 160 | + ) |
| 161 | + |
| 162 | + async def retry(task, error): |
| 163 | + task.attempts += 1 |
| 164 | + if task.attempts < max_retries: |
| 165 | + await redis.lpush("backport_queue", task.model_dump_json()) |
| 166 | + else: |
| 167 | + await redis.lpush("error_list", error) |
| 168 | + |
| 169 | + try: |
| 170 | + output = await agent.run_with_schema(input) |
| 171 | + except Exception as e: |
| 172 | + error = "".join(traceback.format_exception(e)) |
| 173 | + print(error, file=sys.stderr) |
| 174 | + await retry( |
| 175 | + task, ErrorData(details=error, jira_issue=input.jira_issue).model_dump_json() |
| 176 | + ) |
| 177 | + else: |
| 178 | + if output.success: |
| 179 | + await redis.lpush("completed_backport_list", output.model_dump_json()) |
| 180 | + else: |
| 181 | + await retry(task, output.error) |
| 182 | + |
| 183 | + |
| 184 | +if __name__ == "__main__": |
| 185 | + try: |
| 186 | + asyncio.run(main()) |
| 187 | + except FrameworkError as e: |
| 188 | + traceback.print_exc() |
| 189 | + sys.exit(e.explain()) |
0 commit comments