From 170b53ad28d6a7c359f1f9f3d63860e507bd865a Mon Sep 17 00:00:00 2001 From: Emil Simeonov Date: Wed, 17 Jun 2026 18:15:28 +0200 Subject: [PATCH] GRM-1: feat: initial implementation of Gitea Runner Manager --- .ansible-lint | 7 + .checkmake.ini | 3 + .env.example | 4 + .gitignore | 30 ++ .pre-commit-config.yaml | 56 +++ .python-version | 1 + LICENSE | 232 +++++++++ Makefile | 71 +++ README.md | 81 ++++ activate.fish | 6 + activate.sh | 6 + activate.zsh | 7 + ansible/group_vars/all.yml | 3 + ansible/install-runner.yml | 10 + ansible/inventory.example | 3 + ansible/requirements.yml | 5 + ansible/roles/gitea-runner/handlers/main.yml | 9 + .../molecule/default/converge.yml | 10 + .../molecule/default/molecule.yml | 21 + .../gitea-runner/molecule/default/prepare.yml | 9 + .../gitea-runner/molecule/default/verify.yml | 52 ++ ansible/roles/gitea-runner/tasks/config.yml | 13 + ansible/roles/gitea-runner/tasks/docker.yml | 63 +++ .../tasks/download_act_runner.yml | 35 ++ .../gitea-runner/tasks/integration_test.yml | 38 ++ ansible/roles/gitea-runner/tasks/main.yml | 24 + ansible/roles/gitea-runner/tasks/prune.yml | 19 + ansible/roles/gitea-runner/tasks/register.yml | 25 + ansible/roles/gitea-runner/tasks/service.yml | 16 + ansible/roles/gitea-runner/tasks/validate.yml | 24 + .../templates/act-runner-config.toml.j2 | 3 + .../templates/act-runner.service.j2 | 16 + .../templates/docker-prune.service.j2 | 9 + .../templates/docker-prune.timer.j2 | 9 + ansible/roles/gitea-runner/vars/main.yml | 2 + ansible/update-runner.yml | 17 + grm | 7 + initial-plan.md | 454 ++++++++++++++++++ pyproject.toml | 60 +++ setup.py | 3 + src/gitea_runner_manager/__init__.py | 3 + src/gitea_runner_manager/api_client.py | 76 +++ src/gitea_runner_manager/cli.py | 81 ++++ src/gitea_runner_manager/exceptions.py | 27 ++ src/gitea_runner_manager/runner_manager.py | 93 ++++ tests/__init__.py | 1 + tests/integration/__init__.py | 1 + tests/integration/test_provision.py | 33 ++ tests/unit/__init__.py | 1 + tests/unit/test_api_client.py | 120 +++++ tests/unit/test_cli.py | 184 +++++++ tests/unit/test_runner_manager.py | 108 +++++ 52 files changed, 2191 insertions(+) create mode 100644 .ansible-lint create mode 100644 .checkmake.ini create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 .python-version create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 activate.fish create mode 100644 activate.sh create mode 100644 activate.zsh create mode 100644 ansible/group_vars/all.yml create mode 100644 ansible/install-runner.yml create mode 100644 ansible/inventory.example create mode 100644 ansible/requirements.yml create mode 100644 ansible/roles/gitea-runner/handlers/main.yml create mode 100644 ansible/roles/gitea-runner/molecule/default/converge.yml create mode 100644 ansible/roles/gitea-runner/molecule/default/molecule.yml create mode 100644 ansible/roles/gitea-runner/molecule/default/prepare.yml create mode 100644 ansible/roles/gitea-runner/molecule/default/verify.yml create mode 100644 ansible/roles/gitea-runner/tasks/config.yml create mode 100644 ansible/roles/gitea-runner/tasks/docker.yml create mode 100644 ansible/roles/gitea-runner/tasks/download_act_runner.yml create mode 100644 ansible/roles/gitea-runner/tasks/integration_test.yml create mode 100644 ansible/roles/gitea-runner/tasks/main.yml create mode 100644 ansible/roles/gitea-runner/tasks/prune.yml create mode 100644 ansible/roles/gitea-runner/tasks/register.yml create mode 100644 ansible/roles/gitea-runner/tasks/service.yml create mode 100644 ansible/roles/gitea-runner/tasks/validate.yml create mode 100644 ansible/roles/gitea-runner/templates/act-runner-config.toml.j2 create mode 100644 ansible/roles/gitea-runner/templates/act-runner.service.j2 create mode 100644 ansible/roles/gitea-runner/templates/docker-prune.service.j2 create mode 100644 ansible/roles/gitea-runner/templates/docker-prune.timer.j2 create mode 100644 ansible/roles/gitea-runner/vars/main.yml create mode 100644 ansible/update-runner.yml create mode 100755 grm create mode 100644 initial-plan.md create mode 100644 pyproject.toml create mode 100644 setup.py create mode 100644 src/gitea_runner_manager/__init__.py create mode 100644 src/gitea_runner_manager/api_client.py create mode 100644 src/gitea_runner_manager/cli.py create mode 100644 src/gitea_runner_manager/exceptions.py create mode 100644 src/gitea_runner_manager/runner_manager.py create mode 100644 tests/__init__.py create mode 100644 tests/integration/__init__.py create mode 100644 tests/integration/test_provision.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/test_api_client.py create mode 100644 tests/unit/test_cli.py create mode 100644 tests/unit/test_runner_manager.py diff --git a/.ansible-lint b/.ansible-lint new file mode 100644 index 0000000..f3c14d9 --- /dev/null +++ b/.ansible-lint @@ -0,0 +1,7 @@ +# Ansible-lint configuration +exclude_paths: + - .venv/ + - .cache/ + - molecule/ + - .molecule/ + - .pytest_cache/ diff --git a/.checkmake.ini b/.checkmake.ini new file mode 100644 index 0000000..970266c --- /dev/null +++ b/.checkmake.ini @@ -0,0 +1,3 @@ +[checkmake] +# Disable the phony rule which flags common .PHONY placement patterns +# as it produces false positives for standard Makefile layouts diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..eddb359 --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +GITEA_URL=https://git.example.com +GITEA_TOKEN=your-personal-access-token +# Optional: GITEA_RUNNER_USER=ubuntu +# Optional: GITEA_RUNNER_KEY=~/.ssh/id_ed25519 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d5639d9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +# Environment +.env +.venv/ +venv/ + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.egg-info/ +dist/ +build/ + +# IDE +.vscode/ +.idea/ +*.swp +*.swo + +# Ansible +*.retry +.molecule/ + +# Coverage +.coverage +htmlcov/ + +# Misc +*.log +.DS_Store diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..7494a12 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,56 @@ +repos: + - repo: local + hooks: + - id: ruff-lint + name: ruff lint + entry: .venv/bin/ruff check src/ tests/ + language: system + types: [python] + pass_filenames: false + stages: [pre-commit] + + - id: ruff-format + name: ruff format check + entry: .venv/bin/ruff format --check src/ tests/ + language: system + types: [python] + pass_filenames: false + stages: [pre-commit] + + - id: pyright + name: pyright type check + entry: .venv/bin/pyright + language: system + types: [python] + pass_filenames: false + stages: [pre-commit] + + - id: ansible-lint + name: ansible-lint + entry: .venv/bin/ansible-lint ansible/ + language: system + types: [yaml] + pass_filenames: false + stages: [pre-commit] + + - id: detect-secrets + name: detect-secrets + entry: .venv/bin/detect-secrets scan --baseline .secrets.baseline + language: system + pass_filenames: false + stages: [pre-commit] + + - id: pytest-cov + name: pytest with 100% coverage + entry: .venv/bin/pytest tests/unit/ --cov=src/gitea_runner_manager --cov-report=term-missing --cov-fail-under=100 + language: system + types: [python] + pass_filenames: false + stages: [pre-push] + + - id: test-all + name: run all tests + entry: make test-all + language: system + pass_filenames: false + stages: [pre-push] diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..2d4715b --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.11.11 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c71be2f --- /dev/null +++ b/LICENSE @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + grm + Copyright (C) 2026 emil + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + grm Copyright (C) 2026 emil + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..737afbe --- /dev/null +++ b/Makefile @@ -0,0 +1,71 @@ +.PHONY: all setup install update lint ansible-lint makefile-lint lint-all test test-unit pytest-cov molecule test-all clean + +PYTHON := python3 +VENV := .venv +BIN := $(VENV)/bin +CHECKMAKE := $(shell command -v checkmake 2>/dev/null || echo $(HOME)/go/bin/checkmake) + +all: setup + +setup: $(VENV)/bin/activate .env activate-scripts checkmake + $(BIN)/pip install -e ".[dev]" + $(BIN)/ansible-galaxy collection install -r ansible/requirements.yml + $(BIN)/pre-commit install + @echo "Setup complete. Activate the virtual environment with: source .venv/bin/activate" + +.env: + @if [ ! -f .env ]; then \ + cp .env.example .env; \ + echo "Created .env from .env.example — please edit it with your credentials."; \ + fi + +$(VENV)/bin/activate: + $(PYTHON) -m venv $(VENV) + $(BIN)/pip install --upgrade pip setuptools wheel + +activate-scripts: $(VENV)/bin/activate + @test -f activate.sh || (echo '#!/usr/bin/env bash' > activate.sh && echo 'source "$$(cd "$$(dirname "$${BASH_SOURCE[0]}")" && pwd)/.venv/bin/activate"' >> activate.sh && chmod +x activate.sh) + @test -f activate.fish || (echo '#!/usr/bin/env fish' > activate.fish && echo 'set -l script_dir (dirname (status --current-filename))' >> activate.fish && echo 'source "$$script_dir/.venv/bin/activate.fish"' >> activate.fish && chmod +x activate.fish) + @test -f activate.zsh || (echo '#!/usr/bin/env zsh' > activate.zsh && echo '0="$${ZERO:-$${0:#$$ZSH_ARGZERO}}"' >> activate.zsh && echo '0="$${$${(M)0:#/*}:-$$PWD/$$0}"' >> activate.zsh && echo 'source "$${0:A:h}/.venv/bin/activate"' >> activate.zsh && chmod +x activate.zsh) + +checkmake: + @which checkmake >/dev/null 2>&1 || (which go >/dev/null 2>&1 && go install github.com/mrtazz/checkmake/cmd/checkmake@latest) || (echo "Warning: checkmake not installed. Install Go and run: go install github.com/mrtazz/checkmake/cmd/checkmake@latest" && exit 0) + +install: + @if [ -z "$(HOST)" ]; then echo "HOST is required. Example: make install HOST=192.168.1.10"; exit 1; fi + $(BIN)/python grm install $(HOST) $(if $(USER),--user $(USER),) $(if $(KEY),--key $(KEY),) $(if $(NAME),--name $(NAME),) $(if $(TOKEN),--token $(TOKEN),) + +update: + @if [ -z "$(HOST)" ]; then echo "HOST is required. Example: make update HOST=192.168.1.10"; exit 1; fi + $(BIN)/python grm update $(HOST) $(if $(USER),--user $(USER),) $(if $(KEY),--key $(KEY),) $(if $(VERSION),--version $(VERSION),) + +lint: + $(BIN)/ruff check src/ tests/ + $(BIN)/ruff format --check src/ tests/ + $(BIN)/pyright + +ansible-lint: + $(BIN)/ansible-lint ansible/ + +makefile-lint: + @$(CHECKMAKE) Makefile + +lint-all: lint ansible-lint makefile-lint + +test-unit: + $(BIN)/pytest tests/unit/ -v + +pytest-cov: + $(BIN)/pytest tests/unit/ -v --cov=src/gitea_runner_manager --cov-report=term-missing --cov-fail-under=100 + +molecule: + cd ansible/roles/gitea-runner && $(BIN)/molecule test + +test: test-all + +test-all: pytest-cov molecule + +clean: + find . -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true + find . -type f -name "*.pyc" -delete 2>/dev/null || true + rm -rf .coverage htmlcov/ .molecule/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..cb394c9 --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# Gitea Runner Manager (GRM) + +A lean command-line tool to automate the installation, configuration, and lifecycle management of Gitea Actions runners on Arch Linux, Ubuntu, and Debian hosts. + +> **Pronunciation note:** GRM is short for *Gitea Runner Manager*, but say it like **ГРЪМ** (roughly "GRUM" in Latin letters) — the Bulgarian word for **thunder**. Wherever there are clouds, there may be thunders. This is an open-source project from **Oblachno** (облачно means *cloudy* in Bulgarian). + +## Features + +- **Simple and focused** — no unnecessary features. +- **Secure** — no hardcoded secrets, uses scoped tokens. +- **Idempotent** — can be run multiple times safely. +- **Flexible** — accepts a plain IP address or hostname, and allows specifying the SSH user and private key. + +## Supported Operating Systems + +- Arch Linux +- Ubuntu 22.04 / 24.04 / 26.04 +- Debian 12 / 13 + +## Quick Start + +### Developer Setup + +```bash +git clone https://git.oblachno.oblachno.com/oblachno/gitea-runner-manager.git +cd gitea-runner-manager +pyenv install 3.11.11 +pyenv local 3.11.11 +make setup +``` + +### Configure Gitea Credentials + +```bash +cp .env.example .env +# Edit .env: +# GITEA_URL=https://git.example.com +# GITEA_TOKEN=your-personal-access-token +``` + +The token needs `admin:runner` scope. + +### Install a Runner + +Using the CLI: + +```bash +./grm install 192.168.1.10 --user ubuntu --key ~/.ssh/id_ed25519 --name prod-runner +``` + +Using Make: + +```bash +make install HOST=192.168.1.10 USER=ubuntu KEY=~/.ssh/id_ed25519 NAME=prod-runner +``` + +### Verify Runner + +Check Gitea admin UI under **Actions → Runners**. The runner should appear as **Online**. + +### View Logs + +```bash +sudo journalctl -u act-runner- -f +``` + +## Makefile Targets + +| Target | Description | +|--------|-------------| +| `setup` | Full environment setup | +| `install` | Installs a runner on a host | +| `lint` | Runs Python linters | +| `ansible-lint` | Runs `ansible-lint` | +| `test-unit` | Runs unit tests with coverage | +| `molecule` | Runs Ansible Molecule tests | +| `test-all` | Runs all tests | + +## License + +GPL-3.0 \ No newline at end of file diff --git a/activate.fish b/activate.fish new file mode 100644 index 0000000..bbdf3d9 --- /dev/null +++ b/activate.fish @@ -0,0 +1,6 @@ +#!/usr/bin/env fish +# Activate the Python virtual environment for fish +# Usage: source activate.fish + +set -l script_dir (dirname (status --current-filename)) +source "$script_dir/.venv/bin/activate.fish" diff --git a/activate.sh b/activate.sh new file mode 100644 index 0000000..2908cb6 --- /dev/null +++ b/activate.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Activate the Python virtual environment for bash/zsh +# Usage: source activate.sh + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-${(%):-%x}}")" && pwd)" +source "$SCRIPT_DIR/.venv/bin/activate" diff --git a/activate.zsh b/activate.zsh new file mode 100644 index 0000000..0f0861e --- /dev/null +++ b/activate.zsh @@ -0,0 +1,7 @@ +#!/usr/bin/env zsh +# Activate the Python virtual environment for zsh +# Usage: source activate.zsh + +0="${ZERO:-${0:#$ZSH_ARGZERO}}" +0="${${(M)0:#/*}:-$PWD/$0}" +source "${0:A:h}/.venv/bin/activate" diff --git a/ansible/group_vars/all.yml b/ansible/group_vars/all.yml new file mode 100644 index 0000000..c90a759 --- /dev/null +++ b/ansible/group_vars/all.yml @@ -0,0 +1,3 @@ +--- +# Default variables for all hosts +ansible_python_interpreter: /usr/bin/python3 diff --git a/ansible/install-runner.yml b/ansible/install-runner.yml new file mode 100644 index 0000000..1c412ae --- /dev/null +++ b/ansible/install-runner.yml @@ -0,0 +1,10 @@ +--- +- name: Install Gitea Actions runner + hosts: all + become: true + vars: + gitea_url: "{{ gitea_url | mandatory }}" + registration_token: "{{ registration_token | mandatory }}" + runner_name: "{{ runner_name | default(inventory_hostname) }}" + roles: + - role: gitea-runner diff --git a/ansible/inventory.example b/ansible/inventory.example new file mode 100644 index 0000000..2e553a6 --- /dev/null +++ b/ansible/inventory.example @@ -0,0 +1,3 @@ +[runners] +192.168.1.10 ansible_user=ubuntu ansible_ssh_private_key_file=~/.ssh/id_ed25519 +runner.example.com ansible_user=arch diff --git a/ansible/requirements.yml b/ansible/requirements.yml new file mode 100644 index 0000000..0bde23b --- /dev/null +++ b/ansible/requirements.yml @@ -0,0 +1,5 @@ +collections: + - name: community.general + version: ">=13.0.1" + - name: ansible.posix + version: ">=1.5.4" diff --git a/ansible/roles/gitea-runner/handlers/main.yml b/ansible/roles/gitea-runner/handlers/main.yml new file mode 100644 index 0000000..8a40695 --- /dev/null +++ b/ansible/roles/gitea-runner/handlers/main.yml @@ -0,0 +1,9 @@ +--- +- name: Reload systemd + ansible.builtin.systemd: + daemon_reload: true + +- name: Restart act-runner + ansible.builtin.systemd: + name: "act-runner-{{ runner_name }}" + state: restarted diff --git a/ansible/roles/gitea-runner/molecule/default/converge.yml b/ansible/roles/gitea-runner/molecule/default/converge.yml new file mode 100644 index 0000000..dff36dc --- /dev/null +++ b/ansible/roles/gitea-runner/molecule/default/converge.yml @@ -0,0 +1,10 @@ +--- +- name: Converge + hosts: all + become: true + vars: + gitea_url: "http://localhost:3000" + registration_token: "fake-token-for-testing" + runner_name: "molecule-test-runner" + roles: + - role: gitea-runner diff --git a/ansible/roles/gitea-runner/molecule/default/molecule.yml b/ansible/roles/gitea-runner/molecule/default/molecule.yml new file mode 100644 index 0000000..a7c4c5c --- /dev/null +++ b/ansible/roles/gitea-runner/molecule/default/molecule.yml @@ -0,0 +1,21 @@ +--- +driver: + name: docker + +platforms: + - name: instance + image: geerlingguy/docker-ubuntu2204-ansible:latest + command: "" + volumes: + - /sys/fs/cgroup:/sys/fs/cgroup:rw + cgroupns_mode: host + privileged: true + pre_build_image: true + +provisioner: + name: ansible + playbooks: + converge: converge.yml + +verifier: + name: ansible diff --git a/ansible/roles/gitea-runner/molecule/default/prepare.yml b/ansible/roles/gitea-runner/molecule/default/prepare.yml new file mode 100644 index 0000000..2cca80f --- /dev/null +++ b/ansible/roles/gitea-runner/molecule/default/prepare.yml @@ -0,0 +1,9 @@ +--- +- name: Prepare + hosts: all + become: true + tasks: + - name: Update apt cache + ansible.builtin.apt: + update_cache: true + when: ansible_facts['os_family'] == 'Debian' diff --git a/ansible/roles/gitea-runner/molecule/default/verify.yml b/ansible/roles/gitea-runner/molecule/default/verify.yml new file mode 100644 index 0000000..2d44aa2 --- /dev/null +++ b/ansible/roles/gitea-runner/molecule/default/verify.yml @@ -0,0 +1,52 @@ +--- +- name: Verify + hosts: all + become: true + tasks: + - name: Check act_runner binary exists + ansible.builtin.stat: + path: /usr/local/bin/act_runner + register: act_runner_stat + + - name: Assert act_runner binary exists + ansible.builtin.assert: + that: + - act_runner_stat.stat.exists + fail_msg: "act_runner binary is missing" + + - name: Check Docker is installed + ansible.builtin.command: docker --version + changed_when: false + + - name: Check systemd service file exists + ansible.builtin.stat: + path: "/etc/systemd/system/act-runner-molecule-test-runner.service" + register: service_stat + + - name: Assert service file exists + ansible.builtin.assert: + that: + - service_stat.stat.exists + fail_msg: "Systemd service file is missing" + + - name: Check prune timer exists + ansible.builtin.stat: + path: /etc/systemd/system/docker-prune.timer + register: timer_stat + + - name: Assert prune timer exists + ansible.builtin.assert: + that: + - timer_stat.stat.exists + fail_msg: "Docker prune timer is missing" + + - name: Check config file exists + ansible.builtin.stat: + path: /etc/act-runner/config.toml + register: config_stat + + - name: Assert config file exists + ansible.builtin.assert: + that: + - config_stat.stat.exists + fail_msg: "Config file is missing" diff --git a/ansible/roles/gitea-runner/tasks/config.yml b/ansible/roles/gitea-runner/tasks/config.yml new file mode 100644 index 0000000..8f6d5b9 --- /dev/null +++ b/ansible/roles/gitea-runner/tasks/config.yml @@ -0,0 +1,13 @@ +--- +- name: Ensure config directory exists + ansible.builtin.file: + path: /etc/act-runner + state: directory + mode: "0755" + +- name: Create act_runner config file + ansible.builtin.template: + src: act-runner-config.toml.j2 + dest: /etc/act-runner/config.toml + mode: "0644" + notify: Restart act-runner diff --git a/ansible/roles/gitea-runner/tasks/docker.yml b/ansible/roles/gitea-runner/tasks/docker.yml new file mode 100644 index 0000000..8af08b8 --- /dev/null +++ b/ansible/roles/gitea-runner/tasks/docker.yml @@ -0,0 +1,63 @@ +--- +- name: Install Docker (Debian/Ubuntu) + when: ansible_facts['os_family'] == 'Debian' + block: + - name: Install prerequisite packages + ansible.builtin.apt: + name: + - apt-transport-https + - ca-certificates + - curl + - gnupg + state: present + update_cache: true + + - name: Add Docker GPG key + ansible.builtin.apt_key: + url: https://download.docker.com/linux/{{ ansible_distribution | lower }}/gpg + keyring: /etc/apt/keyrings/docker.gpg + when: ansible_distribution != 'Ubuntu' or ansible_distribution_major_version | int >= 22 + + - name: Add Docker repository + ansible.builtin.apt_repository: + repo: >- + deb [arch={{ ansible_architecture }} + signed-by=/etc/apt/keyrings/docker.gpg] + https://download.docker.com/linux/{{ ansible_distribution | lower }} + {{ ansible_distribution_release }} stable + filename: docker + state: present + update_cache: true + + - name: Install Docker packages + ansible.builtin.apt: + name: + - docker-ce + - docker-ce-cli + - containerd.io + - docker-compose-plugin + state: present + +- name: Install Docker (Arch Linux) + when: ansible_facts['os_family'] == 'Archlinux' + block: + - name: Install Docker packages + community.general.pacman: + name: + - docker + - docker-compose + state: present + update_cache: true + +- name: Ensure Docker service is running + ansible.builtin.systemd: + name: docker + state: started + enabled: true + +- name: Add user to docker group + ansible.builtin.user: + name: "{{ ansible_user | default(ansible_user_id) }}" + groups: docker + append: true + when: ansible_user is defined or ansible_user_id is defined diff --git a/ansible/roles/gitea-runner/tasks/download_act_runner.yml b/ansible/roles/gitea-runner/tasks/download_act_runner.yml new file mode 100644 index 0000000..55d7815 --- /dev/null +++ b/ansible/roles/gitea-runner/tasks/download_act_runner.yml @@ -0,0 +1,35 @@ +--- +- name: Get latest act_runner release info + ansible.builtin.uri: + url: https://gitea.com/gitea/act_runner/releases/latest + return_content: true + headers: + Accept: application/json + register: act_runner_release + when: act_runner_version | default('latest') == 'latest' + changed_when: false + +- name: Set act_runner version from latest release + ansible.builtin.set_fact: + act_runner_version: "{{ act_runner_release.json.tag_name }}" + when: act_runner_version | default('latest') == 'latest' + +- name: Set act_runner download URL + ansible.builtin.set_fact: + act_runner_url: >- + https://gitea.com/gitea/act_runner/releases/download/{{ act_runner_version }}/ + act_runner-{{ act_runner_version }}-linux-{{ ansible_architecture | regex_replace('x86_64', 'amd64') }} + +- name: Ensure /usr/local/bin directory exists + ansible.builtin.file: + path: /usr/local/bin + state: directory + mode: "0755" + +- name: Download act_runner binary + ansible.builtin.get_url: + url: "{{ act_runner_url }}" + dest: /usr/local/bin/act_runner + mode: "0755" + force: true + notify: Restart act-runner diff --git a/ansible/roles/gitea-runner/tasks/integration_test.yml b/ansible/roles/gitea-runner/tasks/integration_test.yml new file mode 100644 index 0000000..eb1f806 --- /dev/null +++ b/ansible/roles/gitea-runner/tasks/integration_test.yml @@ -0,0 +1,38 @@ +--- +- name: Wait for runner to appear in Gitea API + ansible.builtin.uri: + url: "{{ gitea_url }}/api/v1/admin/runners" + headers: + Authorization: "token {{ registration_token }}" + method: GET + status_code: 200 + return_content: true + register: runners_response + until: > + runners_response.json.runners | default([]) | + selectattr('name', 'equalto', runner_name) | list | length > 0 + retries: 12 + delay: 10 + when: gitea_url is defined and registration_token is defined + +- name: Verify runner is online + ansible.builtin.uri: + url: "{{ gitea_url }}/api/v1/admin/runners" + headers: + Authorization: "token {{ registration_token }}" + method: GET + status_code: 200 + return_content: true + register: runners_check + when: gitea_url is defined and registration_token is defined + +- name: Fail if runner is not online + ansible.builtin.fail: + msg: "Runner '{{ runner_name }}' is not online in Gitea" + when: + - gitea_url is defined + - registration_token is defined + - > + runners_check.json.runners | default([]) | + selectattr('name', 'equalto', runner_name) | + selectattr('status', 'equalto', 'online') | list | length == 0 diff --git a/ansible/roles/gitea-runner/tasks/main.yml b/ansible/roles/gitea-runner/tasks/main.yml new file mode 100644 index 0000000..c097e98 --- /dev/null +++ b/ansible/roles/gitea-runner/tasks/main.yml @@ -0,0 +1,24 @@ +--- +- name: Include OS-specific Docker installation + ansible.builtin.include_tasks: docker.yml + +- name: Include act_runner download + ansible.builtin.include_tasks: download_act_runner.yml + +- name: Include validation + ansible.builtin.include_tasks: validate.yml + +- name: Include config creation + ansible.builtin.include_tasks: config.yml + +- name: Include registration + ansible.builtin.include_tasks: register.yml + +- name: Include service setup + ansible.builtin.include_tasks: service.yml + +- name: Include prune setup + ansible.builtin.include_tasks: prune.yml + +- name: Include integration test + ansible.builtin.include_tasks: integration_test.yml diff --git a/ansible/roles/gitea-runner/tasks/prune.yml b/ansible/roles/gitea-runner/tasks/prune.yml new file mode 100644 index 0000000..5ff07bc --- /dev/null +++ b/ansible/roles/gitea-runner/tasks/prune.yml @@ -0,0 +1,19 @@ +--- +- name: Create docker-prune service file + ansible.builtin.template: + src: docker-prune.service.j2 + dest: /etc/systemd/system/docker-prune.service + mode: "0644" + +- name: Create docker-prune timer file + ansible.builtin.template: + src: docker-prune.timer.j2 + dest: /etc/systemd/system/docker-prune.timer + mode: "0644" + +- name: Enable and start docker-prune timer + ansible.builtin.systemd: + name: docker-prune.timer + state: started + enabled: true + daemon_reload: true diff --git a/ansible/roles/gitea-runner/tasks/register.yml b/ansible/roles/gitea-runner/tasks/register.yml new file mode 100644 index 0000000..b48744c --- /dev/null +++ b/ansible/roles/gitea-runner/tasks/register.yml @@ -0,0 +1,25 @@ +--- +- name: Ensure work directory exists + ansible.builtin.file: + path: /var/lib/gitea-runner + state: directory + mode: "0755" + +- name: Check if runner is already registered + ansible.builtin.stat: + path: /var/lib/gitea-runner/.runner + register: runner_registered + +- name: Register runner with Gitea + ansible.builtin.command: > + /usr/local/bin/act_runner register + --token {{ registration_token }} + --name {{ runner_name }} + --instance {{ gitea_url }} + --labels ubuntu-latest:docker://node:16-bullseye + --no-interactive + args: + chdir: /var/lib/gitea-runner + when: not runner_registered.stat.exists + register: register_output + changed_when: "'already exists' not in register_output.stdout | default('')" diff --git a/ansible/roles/gitea-runner/tasks/service.yml b/ansible/roles/gitea-runner/tasks/service.yml new file mode 100644 index 0000000..b98468e --- /dev/null +++ b/ansible/roles/gitea-runner/tasks/service.yml @@ -0,0 +1,16 @@ +--- +- name: Create systemd service file + ansible.builtin.template: + src: act-runner.service.j2 + dest: "/etc/systemd/system/act-runner-{{ runner_name }}.service" + mode: "0644" + notify: + - Reload systemd + - Restart act-runner + +- name: Enable and start act-runner service + ansible.builtin.systemd: + name: "act-runner-{{ runner_name }}" + state: started + enabled: true + daemon_reload: true diff --git a/ansible/roles/gitea-runner/tasks/validate.yml b/ansible/roles/gitea-runner/tasks/validate.yml new file mode 100644 index 0000000..020897b --- /dev/null +++ b/ansible/roles/gitea-runner/tasks/validate.yml @@ -0,0 +1,24 @@ +--- +- name: Check act_runner binary exists + ansible.builtin.stat: + path: /usr/local/bin/act_runner + register: act_runner_stat + +- name: Fail if act_runner binary is missing + ansible.builtin.fail: + msg: "act_runner binary not found at /usr/local/bin/act_runner" + when: not act_runner_stat.stat.exists + +- name: Verify act_runner is executable + ansible.builtin.command: /usr/local/bin/act_runner --version + register: act_runner_version_output + changed_when: false + +- name: Verify Docker connectivity + ansible.builtin.command: docker version + register: docker_version_output + changed_when: false + +- name: Set runner_validated fact + ansible.builtin.set_fact: + runner_validated: true diff --git a/ansible/roles/gitea-runner/templates/act-runner-config.toml.j2 b/ansible/roles/gitea-runner/templates/act-runner-config.toml.j2 new file mode 100644 index 0000000..76845e9 --- /dev/null +++ b/ansible/roles/gitea-runner/templates/act-runner-config.toml.j2 @@ -0,0 +1,3 @@ +log.level = "info" +runner.file = ".runner" +container.label = "gitea-runner=true" diff --git a/ansible/roles/gitea-runner/templates/act-runner.service.j2 b/ansible/roles/gitea-runner/templates/act-runner.service.j2 new file mode 100644 index 0000000..c76f302 --- /dev/null +++ b/ansible/roles/gitea-runner/templates/act-runner.service.j2 @@ -0,0 +1,16 @@ +[Unit] +Description=Gitea Actions Runner ({{ runner_name }}) +After=network.target docker.service +Requires=docker.service + +[Service] +Type=simple +ExecStart=/usr/local/bin/act_runner daemon --config /etc/act-runner/config.toml +WorkingDirectory=/var/lib/gitea-runner +Restart=always +RestartSec=5 +User={{ ansible_user | default('root') }} +Group=docker + +[Install] +WantedBy=multi-user.target diff --git a/ansible/roles/gitea-runner/templates/docker-prune.service.j2 b/ansible/roles/gitea-runner/templates/docker-prune.service.j2 new file mode 100644 index 0000000..8c18a90 --- /dev/null +++ b/ansible/roles/gitea-runner/templates/docker-prune.service.j2 @@ -0,0 +1,9 @@ +[Unit] +Description=Docker prune for Gitea runner resources +After=docker.service +Requires=docker.service + +[Service] +Type=oneshot +ExecStart=/usr/bin/docker system prune -f --filter "label=gitea-runner=true" --filter "until=24h" +ExecStart=/usr/bin/docker volume prune -f --filter "label=gitea-runner=true" --filter "until=24h" diff --git a/ansible/roles/gitea-runner/templates/docker-prune.timer.j2 b/ansible/roles/gitea-runner/templates/docker-prune.timer.j2 new file mode 100644 index 0000000..7231bd3 --- /dev/null +++ b/ansible/roles/gitea-runner/templates/docker-prune.timer.j2 @@ -0,0 +1,9 @@ +[Unit] +Description=Daily Docker prune for Gitea runner resources + +[Timer] +OnCalendar=daily +Persistent=true + +[Install] +WantedBy=timers.target diff --git a/ansible/roles/gitea-runner/vars/main.yml b/ansible/roles/gitea-runner/vars/main.yml new file mode 100644 index 0000000..93cc038 --- /dev/null +++ b/ansible/roles/gitea-runner/vars/main.yml @@ -0,0 +1,2 @@ +--- +act_runner_version: "latest" diff --git a/ansible/update-runner.yml b/ansible/update-runner.yml new file mode 100644 index 0000000..6fb14f9 --- /dev/null +++ b/ansible/update-runner.yml @@ -0,0 +1,17 @@ +--- +- name: Update Gitea Actions runner binary + hosts: all + become: true + vars: + act_runner_version: "{{ act_runner_version | default('latest') }}" + tasks: + - name: Include download and validate tasks + ansible.builtin.include_role: + name: gitea-runner + tasks_from: download_act_runner.yml + + - name: Restart act-runner service + ansible.builtin.systemd: + name: "act-runner-{{ runner_name | default(inventory_hostname) }}" + state: restarted + daemon_reload: true diff --git a/grm b/grm new file mode 100755 index 0000000..1a35b58 --- /dev/null +++ b/grm @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Entrypoint for Gitea Runner Manager CLI.""" + +from gitea_runner_manager.cli import cli + +if __name__ == "__main__": + cli() diff --git a/initial-plan.md b/initial-plan.md new file mode 100644 index 0000000..0ade950 --- /dev/null +++ b/initial-plan.md @@ -0,0 +1,454 @@ +# Gitea Runner Manager (GRM) – Complete Project Plan + +--- + +## 1. Overview + +**Gitea Runner Manager (GRM)** is a lean command‑line tool to automate the installation, configuration, and lifecycle management of Gitea Actions runners on **Arch Linux, Ubuntu (22.04, 24.04, 26.04), and Debian (12, 13)** hosts. It is designed to: + +- Be **simple and focused** – no unnecessary features. +- Be **secure** – no hardcoded secrets, uses scoped tokens. +- Be **idempotent** – can be run multiple times safely. +- Be **flexible** – accepts a plain IP address or hostname, and allows specifying the SSH user and private key. + +GRM provides a unified CLI (`grm.py`) and a `make install` target to: + +- List registered runners in a Gitea instance. +- Generate registration tokens. +- Install and configure a runner on a remote host (Docker, `act_runner`, systemd service, safe Docker pruning). +- Update the `act_runner` binary without losing registration. +- (Future) Uninstall a runner. + +--- + +## 2. Key Design Decisions + +| Area | Decision | Rationale | +|------|----------|-----------| +| Target OS | Arch Linux, Ubuntu 22.04/24.04/26.04, Debian 12/13 | Covers 99% of use cases; avoids complexity. | +| Architecture | amd64 only | Hetzner and most cloud providers use x86_64. | +| Backup | Lightweight config backup (optional) | Runner state is stored in Gitea; re‑registration is trivial. | +| Monitoring | None | Gitea UI shows runner status; manual checks are enough. | +| Logging | Systemd `journald` | Sufficient for debugging; no centralised logging needed. | +| Pruning | Only runner‑labelled resources | Prevents accidental deletion of unrelated containers. | +| Integration tests | Run after installation; fail if not successful | Ensures runner is functional from the start. | +| Token storage | `.env` file or `--token` flag | No secrets in code; supports CI/CD. | +| Host specification | Plain IP or hostname; SSH user and key overridable | Simplifies inventory management, works with any host. | + +--- + +## 3. Architecture + +GRM consists of three layers: + +1. **CLI (Python)**: User commands, Gitea API interactions, Ansible invocation. +2. **Ansible Playbook**: Idempotent installation of runner on target host, adapting to OS distribution. +3. **Integration Tests**: Run after installation; verify runner is online in Gitea. + +```text ++----------------+ +----------------+ +-----------------+ +| User / CI | ----> | grm.py CLI | ----> | Gitea API | ++----------------+ +----------------+ +-----------------+ + | + v + +------------------+ + | Ansible Playbook | + +------------------+ + | + v + +------------------+ + | Remote Host | + | (Arch/Ubuntu | + | /Debian) | + +------------------+ + | + v + +------------------+ + | Integration Tests| + | (post-install) | + +------------------+ +``` + +--- + +## 4. Project Structure + +``` +gitea-runner-manager/ +├── .python-version # 3.11.11 +├── .env.example # Environment variables template +├── .gitignore +├── README.md +├── LICENSE (GPL-3.0) +├── Makefile # Targets: setup, install, update, lint, ansible-lint, test, etc. +├── pyproject.toml # Single source for Python dependencies +├── setup.py # Minimal setup for editable install +├── grm.py # CLI entrypoint +├── src/ +│ └── gitea_runner_manager/ +│ ├── __init__.py +│ ├── cli.py # CLI logic (click commands) +│ ├── runner_manager.py # Core logic (API calls, Ansible invocation) +│ ├── api_client.py # Gitea API interactions +│ └── exceptions.py # Custom exceptions +├── tests/ +│ ├── __init__.py +│ ├── unit/ +│ │ ├── test_runner_manager.py +│ │ └── test_api_client.py +│ └── integration/ +│ └── test_provision.py # Integration tests for installation +├── ansible/ +│ ├── requirements.yml # Ansible collections +│ ├── install-runner.yml # Main playbook +│ ├── update-runner.yml # Update playbook (future) +│ ├── inventory.example # Optional static inventory (not required) +│ ├── group_vars/ +│ │ └── all.yml +│ └── roles/ +│ └── gitea-runner/ +│ ├── tasks/ +│ │ ├── main.yml +│ │ ├── docker.yml # Install Docker (OS-specific) +│ │ ├── download_act_runner.yml # Download binary +│ │ ├── validate.yml # Validate binary +│ │ ├── register.yml # Register with Gitea +│ │ ├── config.yml # Create config file +│ │ ├── service.yml # Systemd service +│ │ ├── prune.yml # Docker prune timer +│ │ └── integration_test.yml # Post-install validation +│ ├── handlers/ +│ │ └── main.yml +│ ├── templates/ +│ │ ├── act-runner.service.j2 +│ │ ├── act-runner-config.toml.j2 +│ │ ├── docker-prune.service.j2 +│ │ └── docker-prune.timer.j2 +│ ├── vars/ +│ │ └── main.yml +│ └── molecule/ +│ └── default/ +│ ├── molecule.yml +│ ├── converge.yml +│ ├── verify.yml +│ └── prepare.yml +└── .pre-commit-config.yaml # Pre-commit and pre-push hooks +``` + +--- + +## 5. Python Environment and Dependencies + +- **Python version**: 3.11.11 (managed by pyenv). +- **Virtual environment**: Created automatically by `make setup` (or manually with `python -m venv .venv`). + +**Dependencies** (defined in `pyproject.toml`): + +| Type | Packages | +|------|----------| +| Runtime | `requests`, `python-dotenv`, `click`, `ansible` | +| Development | `pytest`, `pytest-cov`, `ruff`, `pyright`, `molecule`, `molecule-docker`, `ansible-lint`, `pre-commit` | + +All dependencies are installed with `make setup` or `pip install -e .[dev]`. + +--- + +## 6. Makefile (Complete) + +The `Makefile` provides the following targets: + +| Target | Description | +|--------|-------------| +| `setup` | Full environment setup: checks pyenv, installs Python dependencies, Ansible collections, and pre‑commit hooks. | +| `install` | Installs a runner on a host. **Requires `HOST`**, optional `USER`, `KEY`, `NAME`, `TOKEN`. Example: `make install HOST=192.168.1.10 USER=arch NAME=my-runner` | +| `update` | Updates the `act_runner` binary on the specified host (future). | +| `lint` | Runs Python linters (`ruff`, `pyright`). | +| `ansible-lint` | Runs `ansible-lint` on all playbooks and roles. | +| `lint-all` | Runs `lint` and `ansible-lint`. | +| `test-unit` | Runs unit tests with coverage. | +| `pytest-cov` | Runs unit tests with **100% coverage requirement**. | +| `molecule` | Runs Ansible Molecule tests. | +| `test-all` | Runs `pytest-cov` and `molecule`. | +| `clean` | Removes temporary files and caches. | + +**Example usage**: + +```bash +make setup # Initialize development environment + +# Install runner on a host (plain IP) with default user (ansible_user in inventory) +make install HOST=192.168.1.10 + +# With custom user and SSH private key +make install HOST=192.168.1.10 USER=arch KEY=~/.ssh/id_ed25519 + +# With custom runner name and token (token auto-generated if omitted) +make install HOST=runner.example.com USER=ubuntu NAME=prod-runner + +make ansible-lint # Lint Ansible code +make test-all # Run all tests (unit + molecule) +``` + +--- + +## 7. Pre-commit and Pre-push Hooks + +Defined in `.pre-commit-config.yaml`. Hooks run automatically on `git commit` and `git push`. + +| Hook | Stage | Purpose | +|------|-------|---------| +| `ruff-lint` | commit | Lint Python code | +| `ruff-format` | commit | Format Python code | +| `pyright` | commit | Type‑check Python code | +| `ansible-lint` | commit | Lint Ansible playbooks/roles | +| `detect-secrets` | commit | Prevent committing secrets | +| `pytest-cov` | push | **100% unit test coverage** | +| `test-all` | push | Run all tests (unit + molecule) | + +If any hook fails, the commit or push is blocked. + +--- + +## 8. CLI – `grm.py` + +The CLI is built with `click` and provides the following commands: + +```bash +# List all registered runners +./grm.py list + +# Generate a new registration token +./grm.py token + +# Install and configure a runner on a remote host +./grm.py install --user [--key ] [--name ] [--token ] + +# Update runner binary +./grm.py update --user [--key ] [--version ] +``` + +**Options**: +- `--user`: SSH user (default: from environment or `ansible_user` in inventory, fallback to `root`). +- `--key`: Path to private SSH key (optional, uses default key if not provided). +- `--name`: Runner name (default: hostname). +- `--token`: Registration token (auto-generated if not provided). + +**Environment**: +- Reads `.env` file if present. +- Uses `GITEA_URL`, `GITEA_TOKEN`, and optionally `GITEA_RUNNER_USER`, `GITEA_RUNNER_KEY` from environment. + +**Implementation** (`src/gitea_runner_manager/cli.py`): +- `list` → calls `api_client.get_runners()`. +- `token` → calls `api_client.create_registration_token()`. +- `install` → generates token (if not provided), builds an Ansible command with `-i ,` and `--user ` and `--private-key `. +- `update` → similar to install but with the update playbook. + +**Ansible invocation**: +```bash +ansible-playbook install-runner.yml \ + -i "," \ + -u \ + --private-key \ + --extra-vars "registration_token= runner_name=" +``` + +--- + +## 9. Ansible Role – `gitea-runner` + +The role performs the following tasks in order, adapting to the OS distribution using `ansible_facts['os_family']` and `ansible_distribution`. + +### 9.1. `docker.yml` – OS‑specific Docker installation + +- **For Debian/Ubuntu**: + - Install `apt-transport-https`, `ca-certificates`, `curl`. + - Add Docker GPG key and repository. + - Install `docker-ce`, `docker-ce-cli`, `containerd.io`, `docker-compose-plugin`. + +- **For Arch Linux**: + - Install `docker`, `docker-compose` using `pacman`. + - Ensure the `docker` systemd service is enabled and started. + - Add the current user to the `docker` group. + +The playbook detects the OS family and executes the appropriate block. + +### 9.2. `download_act_runner.yml` +- Fetches the latest (or specified) `act_runner` binary from Gitea releases. +- Extracts it to `/usr/local/bin/act_runner` and sets executable permissions. +- Uses `ansible_architecture` to choose the correct binary (`linux_amd64`). + +### 9.3. `validate.yml` +- Checks that `/usr/local/bin/act_runner` exists and is executable. +- Runs `act_runner --version` to ensure it works. +- Checks Docker connectivity (`docker version`). +- Sets `runner_validated: true` if all checks pass. + +### 9.4. `config.yml` +- Creates `/etc/act-runner/config.toml` with the following content: + ```toml + log.level = "info" + runner.file = ".runner" + container.label = "gitea-runner=true" + ``` +- This ensures all spawned containers are labelled, enabling safe pruning. + +### 9.5. `register.yml` +- Ensures work directory (`/var/lib/gitea-runner`) exists. +- Runs `act_runner register` with the provided `registration_token`, `runner_name`, `labels`, and `gitea_url`. +- Skips registration if `.act_runner` already exists (idempotent). + +### 9.6. `service.yml` +- Creates systemd service file `/etc/systemd/system/act-runner-{{ runner_name }}.service`. +- Points to the config file with `--config /etc/act-runner/config.toml`. +- Enables and starts the service. + +### 9.7. `prune.yml` +- Creates systemd service and timer for daily Docker prune: + - `docker-prune.service`: runs `docker system prune` and `docker volume prune` with filters for `label=gitea-runner=true` and `until=24h`. + - `docker-prune.timer`: triggers daily. +- Enables and starts the timer. + +### 9.8. `integration_test.yml` +- Waits up to 2 minutes for the runner to appear in the Gitea API. +- Checks that the runner status is `"online"`. +- Fails the playbook if the runner is not found or not online. +- This ensures that the runner is fully functional after installation. + +--- + +## 10. Integration Tests (Detailed) + +After registration and service start, the playbook runs `integration_test.yml`. It uses the Gitea API to verify the runner is online. The test is written in Ansible and uses the `uri` module. + +**Conditions**: +- Retry every 10 seconds for up to 12 attempts (2 minutes total). +- If the runner is not found or not online, the playbook fails with a clear error message. + +**Why this matters**: +- Catches registration failures early. +- Ensures the runner can communicate with Gitea. +- Prevents deploying a broken runner. + +--- + +## 11. Safe Docker Pruning + +The runner labels all its containers with `gitea-runner=true` (via `container.label` in the config file). The prune service uses `--filter "label=gitea-runner=true"` to ensure it only removes resources created by the runner. This guarantees that other services on the same host are not affected. + +--- + +## 12. Quality Gates + +- **100% unit test coverage** (`make pytest-cov`). +- **All linters pass** (ruff, pyright, ansible-lint). +- **Molecule tests pass** (role validation in Docker container). +- **Integration tests pass** (post‑installation validation). + +These gates are enforced by pre‑push hooks. + +--- + +## 13. Installation & Usage + +### 13.1. Developer Setup + +```bash +git clone https://git.oblachno.oblachno.com/oblachno/gitea-runner-manager.git +cd gitea-runner-manager +pyenv install 3.11.11 +pyenv local 3.11.11 +make setup +``` + +### 13.2. Configure Gitea Credentials + +```bash +cp .env.example .env +# Edit .env: +# GITEA_URL=https://git.oblachno.oblachno.com +# GITEA_TOKEN=your-personal-access-token +# Optional: GITEA_RUNNER_USER=ubuntu # default SSH user +# Optional: GITEA_RUNNER_KEY=~/.ssh/id_rsa +``` + +The token needs `admin:runner` scope (or `admin` for full management). + +### 13.3. Install a Runner + +Using the CLI (recommended for flexibility): + +```bash +./grm.py install 192.168.1.10 --user ubuntu --key ~/.ssh/id_ed25519 --name prod-runner +``` + +Using Make: + +```bash +make install HOST=192.168.1.10 USER=ubuntu KEY=~/.ssh/id_ed25519 NAME=prod-runner +``` + +If `USER` is not provided, the CLI uses the environment variable `GITEA_RUNNER_USER` or falls back to the current local user's username (which may not exist on the remote host – it's better to always specify). + +### 13.4. Verify Runner + +Check Gitea admin UI under **Actions → Runners**. The runner should appear as **Online**. + +### 13.5. Update Runner Binary (Future) + +```bash +./grm.py update 192.168.1.10 --user ubuntu +``` + +--- + +## 14. Molecule Tests + +The Ansible role is tested with Molecule using a systemd‑enabled Docker container. For Arch Linux, we may use a different Docker image (e.g., `archlinux/archlinux`). The test suite will include scenarios for Ubuntu, Debian, and Arch Linux. + +The `default` scenario: +- Verifies Docker installation. +- Checks that `act_runner` binary is present and executable. +- Asserts that the systemd service is enabled and running. +- Ensures the prune timer is active. +- Runs the `integration_test` task with a mock Gitea API (or skips it if `runner_register=false`). + +Molecule tests run as part of `make test-all`. + +--- + +## 15. Logging + +- All Ansible output goes to stdout (visible in CLI). +- `act_runner` logs go to `journald` via the systemd service. +- To view runner logs: `sudo journalctl -u act-runner- -f`. + +--- + +## 16. Future Extensions (Optional) + +- **Uninstall**: A playbook to stop the service, remove the binary, and delete the work directory. +- **Version pinning**: Allow specifying a particular `act_runner` version via CLI. +- **Additional distributions**: Extend the role to support more distros if needed. + +--- + +## 17. Success Criteria + +- [ ] `make setup` configures the development environment. +- [ ] `make install HOST=... USER=...` provisions a runner on Ubuntu, Debian, and Arch Linux. +- [ ] Integration tests pass after installation; installation fails if they do not. +- [ ] Pre‑commit and pre‑push hooks enforce quality gates (100% coverage, linting). +- [ ] Molecule tests pass for all supported OS. +- [ ] Docker prune only affects runner‑labelled resources. +- [ ] `make ansible-lint` runs successfully. +- [ ] Documentation is complete and accurate. + +--- + +## 18. License + +- **GPL‑3.0** – open source, free to use and modify. + +--- + +**This GRM plan is production‑ready, lean, cross‑distribution, and flexible.** It supports Arch, Ubuntu, and Debian, and accepts plain IP addresses with configurable SSH user and key. All components are specified, and the `make setup` command gets a developer from zero to a fully configured environment in minutes. \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..3cb3f88 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,60 @@ +[build-system] +requires = ["setuptools>=61.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "gitea-runner-manager" +version = "0.1.0" +description = "Lean CLI to manage Gitea Actions runners" +readme = "README.md" +license = {text = "GPL-3.0"} +requires-python = ">=3.11" +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", +] +dependencies = [ + "requests>=2.34.2", + "python-dotenv>=1.2.2", + "click>=8.4.1", + "ansible>=14.0.0", +] + +[project.optional-dependencies] +dev = [ + "pytest>=9.1.0", + "pytest-cov>=7.1.0", + "ruff>=0.15.17", + "pyright>=1.1.410", + "molecule>=26.4.0", + "molecule-docker>=2.1.0", + "ansible-lint>=26.4.0", + "pre-commit>=4.6.0", + # Non-Python dev dependency: checkmake (Makefile linter) + # Install via: go install github.com/mrtazz/checkmake/cmd/checkmake@latest +] + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +pythonpath = ["src"] +addopts = "--cov=src/gitea_runner_manager --cov-report=term-missing --cov-fail-under=100" + +[tool.ruff] +target-version = "py311" +line-length = 120 + +[tool.ruff.lint] +select = ["E", "F", "I", "W", "UP", "B", "C4", "SIM"] +ignore = ["SIM117"] + +[tool.ruff.format] +quote-style = "double" +indent-style = "space" + +[tool.pyright] +include = ["src"] +pythonVersion = "3.11" +strict = ["src/gitea_runner_manager"] diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..6068493 --- /dev/null +++ b/setup.py @@ -0,0 +1,3 @@ +from setuptools import setup + +setup() diff --git a/src/gitea_runner_manager/__init__.py b/src/gitea_runner_manager/__init__.py new file mode 100644 index 0000000..b7327f9 --- /dev/null +++ b/src/gitea_runner_manager/__init__.py @@ -0,0 +1,3 @@ +"""Gitea Runner Manager — lean CLI for managing Gitea Actions runners.""" + +__version__ = "0.1.0" diff --git a/src/gitea_runner_manager/api_client.py b/src/gitea_runner_manager/api_client.py new file mode 100644 index 0000000..744a19e --- /dev/null +++ b/src/gitea_runner_manager/api_client.py @@ -0,0 +1,76 @@ +"""Gitea API client for runner management.""" + +from __future__ import annotations + +import os +import time +from typing import Any + +import requests + +from .exceptions import GiteaAPIError, RunnerNotFoundError + + +class GiteaAPIClient: + """Client for interacting with the Gitea API.""" + + def __init__(self, base_url: str, token: str) -> None: + self.base_url = base_url.rstrip("/") + self.token = token + self.session = requests.Session() + self.session.headers.update({"Authorization": f"token {token}"}) + + @classmethod + def from_env(cls) -> GiteaAPIClient: + """Create a client from environment variables.""" + base_url = os.getenv("GITEA_URL", "") + token = os.getenv("GITEA_TOKEN", "") + if not base_url or not token: + raise GiteaAPIError("GITEA_URL and GITEA_TOKEN must be set") + return cls(base_url, token) + + def _request( + self, + method: str, + path: str, + params: dict[str, Any] | None = None, + json: dict[str, Any] | None = None, + ) -> requests.Response: + url = f"{self.base_url}/api/v1{path}" + response = self.session.request(method, url, params=params, json=json) + if not response.ok: + raise GiteaAPIError( + f"Gitea API error: {response.status_code} {response.text}", + status_code=response.status_code, + ) + return response + + def get_runners(self) -> list[dict[str, Any]]: + """List all registered runners.""" + response = self._request("GET", "/admin/runners") + data: dict[str, Any] = response.json() + return data.get("runners", []) + + def create_registration_token(self) -> str: + """Generate a new runner registration token.""" + response = self._request("POST", "/admin/runners/registration-token") + data: dict[str, Any] = response.json() + token = data.get("token") + if not token: + raise GiteaAPIError("No token in response") + return token + + def wait_for_runner(self, name: str, timeout: int = 120, interval: int = 10) -> dict[str, Any]: + """Wait for a runner to appear and be online.""" + elapsed = 0 + effective_interval = max(interval, 1) + while elapsed < timeout: + runners = self.get_runners() + for runner in runners: + if runner.get("name") == name: + if runner.get("status") == "online": + return runner + raise RunnerNotFoundError(f"Runner '{name}' is not online") + time.sleep(effective_interval) + elapsed += effective_interval + raise RunnerNotFoundError(f"Runner '{name}' did not appear within {timeout}s") diff --git a/src/gitea_runner_manager/cli.py b/src/gitea_runner_manager/cli.py new file mode 100644 index 0000000..727eb6d --- /dev/null +++ b/src/gitea_runner_manager/cli.py @@ -0,0 +1,81 @@ +"""Click CLI for Gitea Runner Manager.""" + +from __future__ import annotations + +import builtins +import os +from typing import Any + +import click +from dotenv import load_dotenv # pyright: ignore[reportMissingImports,reportUnknownVariableType] + +from .api_client import GiteaAPIClient +from .exceptions import GRMError +from .runner_manager import RunnerManager + +load_dotenv() + + +@click.group() +@click.version_option(version="0.1.0") +def cli() -> None: + """Gitea Runner Manager — manage Gitea Actions runners.""" + pass + + +@cli.command() +def list() -> None: + """List all registered runners.""" + api = GiteaAPIClient.from_env() + manager = RunnerManager(api) + runners: builtins.list[dict[str, Any]] = manager.list_runners() + if not runners: + click.echo("No runners found.") + return + click.echo(f"{'ID':<6} {'Name':<20} {'Status':<10}") + click.echo("-" * 40) + for runner in runners: + click.echo(f"{runner.get('id', 0):<6} {runner.get('name', 'N/A'):<20} {runner.get('status', 'unknown'):<10}") + + +@cli.command() +def token() -> None: + """Generate a new runner registration token.""" + api = GiteaAPIClient.from_env() + manager = RunnerManager(api) + try: + tok = manager.generate_token() + click.echo(tok) + except GRMError as e: + raise click.ClickException(str(e)) from e + + +@cli.command() +@click.argument("host") +@click.option("--user", "-u", default=lambda: os.getenv("GITEA_RUNNER_USER", os.getlogin()), help="SSH user") +@click.option("--key", "-k", default=lambda: os.getenv("GITEA_RUNNER_KEY"), help="Path to SSH private key") +@click.option("--name", "-n", help="Runner name (default: host)") +@click.option("--token", "-t", help="Registration token (auto-generated if omitted)") +def install(host: str, user: str, key: str | None, name: str | None, token: str | None) -> None: + """Install and configure a runner on a remote host.""" + api = GiteaAPIClient.from_env() + manager = RunnerManager(api) + try: + manager.install(host=host, user=user, key=key, name=name, token=token) + except GRMError as e: + raise click.ClickException(str(e)) from e + + +@cli.command() +@click.argument("host") +@click.option("--user", "-u", default=lambda: os.getenv("GITEA_RUNNER_USER", os.getlogin()), help="SSH user") +@click.option("--key", "-k", default=lambda: os.getenv("GITEA_RUNNER_KEY"), help="Path to SSH private key") +@click.option("--version", "-v", help="Specific act_runner version") +def update(host: str, user: str, key: str | None, version: str | None) -> None: + """Update the act_runner binary on a remote host.""" + api = GiteaAPIClient.from_env() + manager = RunnerManager(api) + try: + manager.update(host=host, user=user, key=key, version=version) + except GRMError as e: + raise click.ClickException(str(e)) from e diff --git a/src/gitea_runner_manager/exceptions.py b/src/gitea_runner_manager/exceptions.py new file mode 100644 index 0000000..54803c0 --- /dev/null +++ b/src/gitea_runner_manager/exceptions.py @@ -0,0 +1,27 @@ +"""Custom exceptions for Gitea Runner Manager.""" + + +class GRMError(Exception): + """Base exception for all Gitea Runner Manager errors.""" + + pass + + +class GiteaAPIError(GRMError): + """Raised when the Gitea API returns an error.""" + + def __init__(self, message: str, status_code: int = 0) -> None: + super().__init__(message) + self.status_code = status_code + + +class AnsibleError(GRMError): + """Raised when an Ansible command fails.""" + + pass + + +class RunnerNotFoundError(GRMError): + """Raised when a runner is not found in Gitea.""" + + pass diff --git a/src/gitea_runner_manager/runner_manager.py b/src/gitea_runner_manager/runner_manager.py new file mode 100644 index 0000000..c436aa2 --- /dev/null +++ b/src/gitea_runner_manager/runner_manager.py @@ -0,0 +1,93 @@ +"""Core logic for managing Gitea runners.""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path +from typing import Any + +from .api_client import GiteaAPIClient +from .exceptions import AnsibleError + + +class RunnerManager: + """Orchestrates runner installation and updates.""" + + def __init__(self, api_client: GiteaAPIClient) -> None: + self.api = api_client + + def list_runners(self) -> list[dict[str, Any]]: + """List all registered runners.""" + return self.api.get_runners() + + def generate_token(self) -> str: + """Generate a new registration token.""" + return self.api.create_registration_token() + + def install( + self, + host: str, + user: str, + key: str | None = None, + name: str | None = None, + token: str | None = None, + ) -> None: + """Install a runner on a remote host using Ansible.""" + if not name: + name = host + if not token: + token = self.generate_token() + + playbook = Path(__file__).parent.parent.parent / "ansible" / "install-runner.yml" + if not playbook.exists(): + raise AnsibleError(f"Playbook not found: {playbook}") + + cmd = [ + "ansible-playbook", + str(playbook), + "-i", + f"{host},", + "-u", + user, + "--extra-vars", + f"registration_token={token} runner_name={name} gitea_url={self.api.base_url}", + ] + if key: + cmd.extend(["--private-key", key]) + + self._run_ansible(cmd) + + def update( + self, + host: str, + user: str, + key: str | None = None, + version: str | None = None, + ) -> None: + """Update the act_runner binary on a remote host.""" + playbook = Path(__file__).parent.parent.parent / "ansible" / "update-runner.yml" + if not playbook.exists(): + raise AnsibleError(f"Playbook not found: {playbook}") + + cmd = [ + "ansible-playbook", + str(playbook), + "-i", + f"{host},", + "-u", + user, + ] + if key: + cmd.extend(["--private-key", key]) + if version: + cmd.extend(["--extra-vars", f"act_runner_version={version}"]) + + self._run_ansible(cmd) + + def _run_ansible(self, cmd: list[str]) -> None: + """Execute an Ansible command, streaming output.""" + env = os.environ.copy() + result = subprocess.run(cmd, env=env, check=False) # noqa: S603 + if result.returncode != 0: + raise AnsibleError(f"Ansible failed with exit code {result.returncode}") diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..7800c29 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for Gitea Runner Manager.""" diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000..c210fac --- /dev/null +++ b/tests/integration/__init__.py @@ -0,0 +1 @@ +"""Integration tests.""" diff --git a/tests/integration/test_provision.py b/tests/integration/test_provision.py new file mode 100644 index 0000000..0ae7802 --- /dev/null +++ b/tests/integration/test_provision.py @@ -0,0 +1,33 @@ +"""Integration tests for runner provisioning.""" + +from unittest.mock import MagicMock, patch + +from gitea_runner_manager.runner_manager import RunnerManager + + +class TestProvisionIntegration: + def test_full_install_flow(self) -> None: + api = MagicMock() + api.base_url = "https://git.example.com" + api.create_registration_token.return_value = "test-token" + manager = RunnerManager(api) + + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=0) + manager.install("192.168.1.10", "ubuntu", name="integration-runner") + mock_run.assert_called_once() + cmd = mock_run.call_args[0][0] + assert "install-runner.yml" in " ".join(cmd) + assert "registration_token=test-token" in " ".join(cmd) + assert "runner_name=integration-runner" in " ".join(cmd) + + def test_update_flow(self) -> None: + api = MagicMock() + manager = RunnerManager(api) + + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=0) + manager.update("192.168.1.10", "ubuntu") + mock_run.assert_called_once() + cmd = mock_run.call_args[0][0] + assert "update-runner.yml" in " ".join(cmd) diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e0310a0 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1 @@ +"""Unit tests.""" diff --git a/tests/unit/test_api_client.py b/tests/unit/test_api_client.py new file mode 100644 index 0000000..335bc5d --- /dev/null +++ b/tests/unit/test_api_client.py @@ -0,0 +1,120 @@ +"""Unit tests for api_client module.""" + +from unittest.mock import MagicMock, patch + +import pytest + +from gitea_runner_manager.api_client import GiteaAPIClient +from gitea_runner_manager.exceptions import GiteaAPIError, RunnerNotFoundError + + +class TestGiteaAPIClient: + def test_init(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token123") + assert client.base_url == "https://git.example.com" + assert client.token == "token123" + assert client.session.headers["Authorization"] == "token token123" + + def test_init_strips_trailing_slash(self) -> None: + client = GiteaAPIClient("https://git.example.com/", "token123") + assert client.base_url == "https://git.example.com" + + def test_from_env_success(self) -> None: + with patch.dict("os.environ", {"GITEA_URL": "https://git.example.com", "GITEA_TOKEN": "tok"}): + client = GiteaAPIClient.from_env() + assert client.base_url == "https://git.example.com" + assert client.token == "tok" + + def test_from_env_missing_url(self) -> None: + with patch.dict("os.environ", {"GITEA_URL": "", "GITEA_TOKEN": "tok"}, clear=True): + with pytest.raises(GiteaAPIError, match="GITEA_URL and GITEA_TOKEN must be set"): + GiteaAPIClient.from_env() + + def test_from_env_missing_token(self) -> None: + with patch.dict("os.environ", {"GITEA_URL": "https://git.example.com", "GITEA_TOKEN": ""}, clear=True): + with pytest.raises(GiteaAPIError, match="GITEA_URL and GITEA_TOKEN must be set"): + GiteaAPIClient.from_env() + + def test_request_success(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token") + mock_response = MagicMock() + mock_response.ok = True + mock_response.status_code = 200 + with patch.object(client.session, "request", return_value=mock_response) as mock_req: + resp = client._request("GET", "/test") + assert resp == mock_response + mock_req.assert_called_once_with("GET", "https://git.example.com/api/v1/test", params=None, json=None) + + def test_request_failure(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token") + mock_response = MagicMock() + mock_response.ok = False + mock_response.status_code = 404 + mock_response.text = "Not Found" + with patch.object(client.session, "request", return_value=mock_response): + with pytest.raises(GiteaAPIError, match="404 Not Found") as exc_info: + client._request("GET", "/test") + assert exc_info.value.status_code == 404 + + def test_get_runners(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token") + mock_response = MagicMock() + mock_response.ok = True + mock_response.json.return_value = {"runners": [{"id": 1, "name": "r1"}]} + with patch.object(client.session, "request", return_value=mock_response): + runners = client.get_runners() + assert runners == [{"id": 1, "name": "r1"}] + + def test_get_runners_empty(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token") + mock_response = MagicMock() + mock_response.ok = True + mock_response.json.return_value = {} + with patch.object(client.session, "request", return_value=mock_response): + runners = client.get_runners() + assert runners == [] + + def test_create_registration_token(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token") + mock_response = MagicMock() + mock_response.ok = True + mock_response.json.return_value = {"token": "reg-token-123"} + with patch.object(client.session, "request", return_value=mock_response): + token = client.create_registration_token() + assert token == "reg-token-123" + + def test_create_registration_token_no_token(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token") + mock_response = MagicMock() + mock_response.ok = True + mock_response.json.return_value = {} + with patch.object(client.session, "request", return_value=mock_response): + with pytest.raises(GiteaAPIError, match="No token in response"): + client.create_registration_token() + + def test_wait_for_runner_success(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token") + mock_response = MagicMock() + mock_response.ok = True + mock_response.json.return_value = {"runners": [{"name": "runner1", "status": "online"}]} + with patch.object(client.session, "request", return_value=mock_response): + runner = client.wait_for_runner("runner1", timeout=5) + assert runner["name"] == "runner1" + + def test_wait_for_runner_not_online(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token") + mock_response = MagicMock() + mock_response.ok = True + mock_response.json.return_value = {"runners": [{"name": "runner1", "status": "offline"}]} + with patch.object(client.session, "request", return_value=mock_response): + with pytest.raises(RunnerNotFoundError, match="is not online"): + client.wait_for_runner("runner1", timeout=5) + + def test_wait_for_runner_timeout(self) -> None: + client = GiteaAPIClient("https://git.example.com", "token") + mock_response = MagicMock() + mock_response.ok = True + mock_response.json.return_value = {"runners": []} + with patch.object(client.session, "request", return_value=mock_response): + with pytest.raises(RunnerNotFoundError, match="did not appear within"): + client.wait_for_runner("runner1", timeout=1, interval=1) diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py new file mode 100644 index 0000000..6517f66 --- /dev/null +++ b/tests/unit/test_cli.py @@ -0,0 +1,184 @@ +"""Unit tests for cli module.""" + +from unittest.mock import MagicMock, patch + +from click.testing import CliRunner + +from gitea_runner_manager.cli import cli + + +class TestCLI: + def test_cli_version(self) -> None: + runner = CliRunner() + result = runner.invoke(cli, ["--version"]) + assert result.exit_code == 0 + assert "0.1.0" in result.output + + @patch("gitea_runner_manager.cli.GiteaAPIClient") + @patch("gitea_runner_manager.cli.RunnerManager") + def test_list_runners(self, mock_manager_class: MagicMock, mock_client_class: MagicMock) -> None: + mock_client = MagicMock() + mock_client_class.from_env.return_value = mock_client + mock_manager = MagicMock() + mock_manager.list_runners.return_value = [ + {"id": 1, "name": "runner1", "status": "online"}, + ] + mock_manager_class.return_value = mock_manager + + runner = CliRunner() + result = runner.invoke(cli, ["list"]) + assert result.exit_code == 0 + assert "runner1" in result.output + assert "online" in result.output + + @patch("gitea_runner_manager.cli.GiteaAPIClient") + @patch("gitea_runner_manager.cli.RunnerManager") + def test_list_empty(self, mock_manager_class: MagicMock, mock_client_class: MagicMock) -> None: + mock_client = MagicMock() + mock_client_class.from_env.return_value = mock_client + mock_manager = MagicMock() + mock_manager.list_runners.return_value = [] + mock_manager_class.return_value = mock_manager + + runner = CliRunner() + result = runner.invoke(cli, ["list"]) + assert result.exit_code == 0 + assert "No runners found" in result.output + + @patch("gitea_runner_manager.cli.GiteaAPIClient") + @patch("gitea_runner_manager.cli.RunnerManager") + def test_token(self, mock_manager_class: MagicMock, mock_client_class: MagicMock) -> None: + mock_client = MagicMock() + mock_client_class.from_env.return_value = mock_client + mock_manager = MagicMock() + mock_manager.generate_token.return_value = "tok123" + mock_manager_class.return_value = mock_manager + + runner = CliRunner() + result = runner.invoke(cli, ["token"]) + assert result.exit_code == 0 + assert "tok123" in result.output + + @patch("gitea_runner_manager.cli.GiteaAPIClient") + @patch("gitea_runner_manager.cli.RunnerManager") + def test_token_error(self, mock_manager_class: MagicMock, mock_client_class: MagicMock) -> None: + mock_client = MagicMock() + mock_client_class.from_env.return_value = mock_client + mock_manager = MagicMock() + from gitea_runner_manager.exceptions import GiteaAPIError + + mock_manager.generate_token.side_effect = GiteaAPIError("boom") + mock_manager_class.return_value = mock_manager + + runner = CliRunner() + result = runner.invoke(cli, ["token"]) + assert result.exit_code != 0 + assert "boom" in result.output + + @patch("gitea_runner_manager.cli.GiteaAPIClient") + @patch("gitea_runner_manager.cli.RunnerManager") + def test_install(self, mock_manager_class: MagicMock, mock_client_class: MagicMock) -> None: + mock_client = MagicMock() + mock_client_class.from_env.return_value = mock_client + mock_manager = MagicMock() + mock_manager_class.return_value = mock_manager + + runner = CliRunner() + result = runner.invoke(cli, ["install", "host1", "--user", "ubuntu"]) + assert result.exit_code == 0 + mock_manager.install.assert_called_once_with(host="host1", user="ubuntu", key=None, name=None, token=None) + + @patch("gitea_runner_manager.cli.GiteaAPIClient") + @patch("gitea_runner_manager.cli.RunnerManager") + def test_install_with_options(self, mock_manager_class: MagicMock, mock_client_class: MagicMock) -> None: + mock_client = MagicMock() + mock_client_class.from_env.return_value = mock_client + mock_manager = MagicMock() + mock_manager_class.return_value = mock_manager + + runner = CliRunner() + result = runner.invoke( + cli, + [ + "install", + "host1", + "--user", + "ubuntu", + "--key", + "/key", + "--name", + "r1", + "--token", + "tok", + ], + ) + assert result.exit_code == 0 + mock_manager.install.assert_called_once_with( + host="host1", + user="ubuntu", + key="/key", + name="r1", + token="tok", + ) + + @patch("gitea_runner_manager.cli.GiteaAPIClient") + @patch("gitea_runner_manager.cli.RunnerManager") + def test_install_error(self, mock_manager_class: MagicMock, mock_client_class: MagicMock) -> None: + mock_client = MagicMock() + mock_client_class.from_env.return_value = mock_client + mock_manager = MagicMock() + from gitea_runner_manager.exceptions import AnsibleError + + mock_manager.install.side_effect = AnsibleError("fail") + mock_manager_class.return_value = mock_manager + + runner = CliRunner() + result = runner.invoke(cli, ["install", "host1", "--user", "ubuntu"]) + assert result.exit_code != 0 + assert "fail" in result.output + + @patch("gitea_runner_manager.cli.GiteaAPIClient") + @patch("gitea_runner_manager.cli.RunnerManager") + def test_update(self, mock_manager_class: MagicMock, mock_client_class: MagicMock) -> None: + mock_client = MagicMock() + mock_client_class.from_env.return_value = mock_client + mock_manager = MagicMock() + mock_manager_class.return_value = mock_manager + + runner = CliRunner() + result = runner.invoke( + cli, + [ + "update", + "host1", + "--user", + "ubuntu", + "--key", + "/key", + "--version", + "v0.2.0", + ], + ) + assert result.exit_code == 0 + mock_manager.update.assert_called_once_with( + host="host1", + user="ubuntu", + key="/key", + version="v0.2.0", + ) + + @patch("gitea_runner_manager.cli.GiteaAPIClient") + @patch("gitea_runner_manager.cli.RunnerManager") + def test_update_error(self, mock_manager_class: MagicMock, mock_client_class: MagicMock) -> None: + mock_client = MagicMock() + mock_client_class.from_env.return_value = mock_client + mock_manager = MagicMock() + from gitea_runner_manager.exceptions import AnsibleError + + mock_manager.update.side_effect = AnsibleError("fail") + mock_manager_class.return_value = mock_manager + + runner = CliRunner() + result = runner.invoke(cli, ["update", "host1", "--user", "ubuntu"]) + assert result.exit_code != 0 + assert "fail" in result.output diff --git a/tests/unit/test_runner_manager.py b/tests/unit/test_runner_manager.py new file mode 100644 index 0000000..2f06773 --- /dev/null +++ b/tests/unit/test_runner_manager.py @@ -0,0 +1,108 @@ +"""Unit tests for runner_manager module.""" + +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest + +from gitea_runner_manager.api_client import GiteaAPIClient +from gitea_runner_manager.exceptions import AnsibleError +from gitea_runner_manager.runner_manager import RunnerManager + + +class TestRunnerManager: + def test_list_runners(self) -> None: + api = MagicMock(spec=GiteaAPIClient) + api.get_runners.return_value = [{"id": 1, "name": "r1"}] + manager = RunnerManager(api) + runners = manager.list_runners() + assert runners == [{"id": 1, "name": "r1"}] + + def test_generate_token(self) -> None: + api = MagicMock(spec=GiteaAPIClient) + api.create_registration_token.return_value = "token123" + manager = RunnerManager(api) + token = manager.generate_token() + assert token == "token123" + + def test_install_without_name_or_token(self) -> None: + api = MagicMock(spec=GiteaAPIClient) + api.base_url = "https://git.example.com" + api.create_registration_token.return_value = "auto-token" + manager = RunnerManager(api) + + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=0) + manager.install("192.168.1.10", "ubuntu") + mock_run.assert_called_once() + cmd = mock_run.call_args[0][0] + cmd_str = " ".join(cmd) + assert "ansible-playbook" in cmd_str + assert "192.168.1.10," in cmd_str + assert "-u" in cmd_str + assert "ubuntu" in cmd_str + assert "registration_token=auto-token" in cmd_str + assert "runner_name=192.168.1.10" in cmd_str + assert "gitea_url=https://git.example.com" in cmd_str + + def test_install_with_name_and_token(self) -> None: + api = MagicMock(spec=GiteaAPIClient) + api.base_url = "https://git.example.com" + manager = RunnerManager(api) + + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=0) + manager.install("host1", "root", key="/key", name="my-runner", token="preset") + cmd = mock_run.call_args[0][0] + cmd_str = " ".join(cmd) + assert "--private-key" in cmd_str + assert "/key" in cmd_str + assert "registration_token=preset" in cmd_str + assert "runner_name=my-runner" in cmd_str + api.create_registration_token.assert_not_called() + + def test_install_playbook_not_found(self) -> None: + api = MagicMock(spec=GiteaAPIClient) + api.base_url = "https://git.example.com" + manager = RunnerManager(api) + with patch.object(Path, "exists", return_value=False): + with pytest.raises(AnsibleError, match="Playbook not found"): + manager.install("host", "user") + + def test_install_ansible_failure(self) -> None: + api = MagicMock(spec=GiteaAPIClient) + api.base_url = "https://git.example.com" + api.create_registration_token.return_value = "tok" + manager = RunnerManager(api) + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=1) + with pytest.raises(AnsibleError, match="Ansible failed with exit code 1"): + manager.install("host", "user") + + def test_update(self) -> None: + api = MagicMock(spec=GiteaAPIClient) + manager = RunnerManager(api) + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=0) + manager.update("host", "user", key="/key", version="v0.2.0") + cmd = mock_run.call_args[0][0] + cmd_str = " ".join(cmd) + assert "update-runner.yml" in cmd_str + assert "--private-key" in cmd_str + assert "/key" in cmd_str + assert "act_runner_version=v0.2.0" in cmd_str + + def test_update_playbook_not_found(self) -> None: + api = MagicMock(spec=GiteaAPIClient) + manager = RunnerManager(api) + with patch.object(Path, "exists", return_value=False): + with pytest.raises(AnsibleError, match="Playbook not found"): + manager.update("host", "user") + + def test_update_ansible_failure(self) -> None: + api = MagicMock(spec=GiteaAPIClient) + manager = RunnerManager(api) + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=2) + with pytest.raises(AnsibleError, match="Ansible failed with exit code 2"): + manager.update("host", "user")