forked from admin/brencher
Compare commits
25
Commits
blank_patch
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83b50af9b3 | ||
|
|
cd1fc53688 | ||
|
|
359c5c4020 | ||
|
|
f70c0a1d12 | ||
|
|
638c2a7e80 | ||
|
|
710b78a528 | ||
|
|
2e48d11b77 | ||
|
|
7938f4f0f0 | ||
|
|
52692a75b8 | ||
|
|
ddce27f1af | ||
|
|
33caa4cb9f | ||
|
|
a9de490ebe | ||
|
|
920249ec30 | ||
|
|
75126cb2fd | ||
|
|
0e83458044 | ||
|
|
7dc36d7487 | ||
|
|
b0e32f835a | ||
|
|
1c0580750d | ||
|
|
8059cc74ea | ||
|
|
e690f6a50c | ||
|
|
98ee950a1f | ||
|
|
e4f90b1f23 | ||
|
|
ba17865a49 | ||
|
|
70f4a4163e | ||
|
|
e5331745be |
@@ -20,16 +20,16 @@ jobs:
|
|||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.PUSH_TOKEN }}
|
||||||
|
|
||||||
- name: Configure git
|
- name: Configure git
|
||||||
run: |
|
run: |
|
||||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
git config user.email "gitea-actions[bot]@noreply.localhost"
|
||||||
git config user.name "GitHub Actions"
|
git config user.name "Gitea Actions"
|
||||||
|
|
||||||
- name: Fetch all branches
|
- name: Fetch all branches
|
||||||
run: |
|
run: |
|
||||||
git remote set-url origin "https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git"
|
git remote set-url origin "https://x-access-token:${PUSH_TOKEN}@gitea.rudolf.keenetic.link/${GITHUB_REPOSITORY}.git"
|
||||||
git fetch --all --prune
|
git fetch --all --prune
|
||||||
|
|
||||||
- name: Merge every branch onto main
|
- name: Merge every branch onto main
|
||||||
@@ -37,7 +37,6 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -eo pipefail
|
set -eo pipefail
|
||||||
MAIN=main
|
MAIN=main
|
||||||
# Collect remote branch names (exclude HEAD and main)
|
|
||||||
branches=$(git for-each-ref --format='%(refname:short)' refs/remotes/origin/ \
|
branches=$(git for-each-ref --format='%(refname:short)' refs/remotes/origin/ \
|
||||||
| sed 's|^origin/||' \
|
| sed 's|^origin/||' \
|
||||||
| grep -v -e '^HEAD$' -e '^main$' -e '^origin$' \
|
| grep -v -e '^HEAD$' -e '^main$' -e '^origin$' \
|
||||||
@@ -49,11 +48,8 @@ jobs:
|
|||||||
continue
|
continue
|
||||||
fi
|
fi
|
||||||
echo "=== Processing branch: $br ==="
|
echo "=== Processing branch: $br ==="
|
||||||
# Create/update a local branch from remote
|
|
||||||
git checkout -B "$br" "origin/$br"
|
git checkout -B "$br" "origin/$br"
|
||||||
# Merge origin/main into branch (non-interactive)
|
|
||||||
if git merge --no-edit "origin/$MAIN"; then
|
if git merge --no-edit "origin/$MAIN"; then
|
||||||
# Push updated branch to remote (no force)
|
|
||||||
if git push origin "$br"; then
|
if git push origin "$br"; then
|
||||||
echo "Pushed merged $br"
|
echo "Pushed merged $br"
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -18,16 +18,16 @@ jobs:
|
|||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
token: ${{ secrets.PUSH_TOKEN }}
|
||||||
|
|
||||||
- name: Configure git
|
- name: Configure git
|
||||||
run: |
|
run: |
|
||||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
git config user.email "gitea-actions[bot]@noreply.localhost"
|
||||||
git config user.name "GitHub Actions"
|
git config user.name "Gitea Actions"
|
||||||
|
|
||||||
- name: Fetch all branches
|
- name: Fetch all branches
|
||||||
run: |
|
run: |
|
||||||
git remote set-url origin "https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git"
|
git remote set-url origin "https://x-access-token:${PUSH_TOKEN}@gitea.rudolf.keenetic.link/${GITHUB_REPOSITORY}.git"
|
||||||
git fetch --all --prune
|
git fetch --all --prune
|
||||||
|
|
||||||
- name: Merge every branch onto main
|
- name: Merge every branch onto main
|
||||||
@@ -35,7 +35,6 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
set -eo pipefail
|
set -eo pipefail
|
||||||
MAIN=main
|
MAIN=main
|
||||||
# Collect remote branch names (exclude HEAD and main)
|
|
||||||
branches=$(git for-each-ref --format='%(refname:short)' refs/remotes/origin/ \
|
branches=$(git for-each-ref --format='%(refname:short)' refs/remotes/origin/ \
|
||||||
| sed 's|^origin/||' \
|
| sed 's|^origin/||' \
|
||||||
| grep -v -e '^HEAD$' -e '^main$' -e '^origin$' \
|
| grep -v -e '^HEAD$' -e '^main$' -e '^origin$' \
|
||||||
@@ -47,12 +46,9 @@ jobs:
|
|||||||
continue
|
continue
|
||||||
fi
|
fi
|
||||||
echo "=== Processing branch: $br ==="
|
echo "=== Processing branch: $br ==="
|
||||||
# Create/update a local branch from remote
|
|
||||||
git reset --hard HEAD
|
git reset --hard HEAD
|
||||||
git checkout -B "$br" "origin/$br"
|
git checkout -B "$br" "origin/$br"
|
||||||
# Merge origin/main into branch (non-interactive)
|
|
||||||
if git merge --no-edit --squash "origin/$MAIN"; then
|
if git merge --no-edit --squash "origin/$MAIN"; then
|
||||||
# Push updated branch to remote (no force)
|
|
||||||
git reset --soft "origin/$MAIN"
|
git reset --soft "origin/$MAIN"
|
||||||
git commit -m "Squash"
|
git commit -m "Squash"
|
||||||
if git push origin "$br" --force-with-lease; then
|
if git push origin "$br" --force-with-lease; then
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
|
|
||||||
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python
|
|
||||||
|
|
||||||
name: Python package
|
name: Python package
|
||||||
|
|
||||||
on:
|
on:
|
||||||
@@ -10,73 +7,40 @@ on:
|
|||||||
pull_request:
|
pull_request:
|
||||||
branches: [ "main" ]
|
branches: [ "main" ]
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
python-version: [
|
python-version: ["3.12.3", "3.13", "3.14"]
|
||||||
# "3.11.3",
|
|
||||||
"3.12.3",
|
|
||||||
"3.13",
|
|
||||||
"3.14",
|
|
||||||
# "3.15",
|
|
||||||
]
|
|
||||||
checker: [
|
|
||||||
"python -c \"import sys; print(f'Python {sys.version}'); print(f'Build: {sys.version_info}'); print(f'Implementation: {sys.implementation}')\"",
|
|
||||||
"pip list",
|
|
||||||
"flake8 . --count --select=E9,F63,F7,F82 --ignore=F824 --show-source --statistics",
|
|
||||||
"flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics",
|
|
||||||
# "ty check backend",
|
|
||||||
"mypy --no-incremental --config-file mypy.ini backend tests",
|
|
||||||
]
|
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Set up Python ${{ matrix.python-version }}, ${{ matrix.checker }}
|
|
||||||
uses: actions/setup-python@v3
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
|
uses: actions/setup-python@v5
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
|
cache: 'pip'
|
||||||
|
cache-dependency-path: |
|
||||||
|
requirements.txt
|
||||||
|
requirements-dev.txt
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip
|
python -m pip install --upgrade pip
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
pip install -r requirements-dev.txt
|
pip install -r requirements-dev.txt
|
||||||
- name: Run checker
|
|
||||||
run: ${{ matrix.checker }}
|
|
||||||
|
|
||||||
tests:
|
- name: Lint (flake8)
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs: build
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
python-version: [
|
|
||||||
# "3.11.3",
|
|
||||||
"3.12.3",
|
|
||||||
"3.13",
|
|
||||||
"3.14",
|
|
||||||
# "3.15",
|
|
||||||
]
|
|
||||||
checker: [
|
|
||||||
"pytest",
|
|
||||||
]
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- name: Set up Python ${{ matrix.python-version }}, ${{ matrix.checker }}
|
|
||||||
uses: actions/setup-python@v3
|
|
||||||
with:
|
|
||||||
python-version: ${{ matrix.python-version }}
|
|
||||||
- name: Install dependencies
|
|
||||||
run: |
|
run: |
|
||||||
# sudo apt-get update
|
flake8 . --count --select=E9,F63,F7,F82 --ignore=F824 --show-source --statistics
|
||||||
# sudo apt-get upgrade -y
|
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
|
||||||
# sudo apt-get install -y --no-install-recommends git docker.io
|
|
||||||
python -m pip install --upgrade pip
|
|
||||||
pip install -r requirements-dev.txt
|
|
||||||
playwright install --with-deps chromium
|
|
||||||
- name: Run checker
|
|
||||||
run: "pytest"
|
|
||||||
|
|
||||||
|
|
||||||
|
- name: Type-check (mypy)
|
||||||
|
run: mypy --no-incremental --config-file mypy.ini backend tests
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
# Adding a new stack to brencher
|
||||||
|
|
||||||
|
A "stack" is one self-contained Docker Swarm service that brencher manages
|
||||||
|
end-to-end: detect HEAD changes, build, deploy, and expose service status to
|
||||||
|
the UI. This file documents how to wire one up so it picks up commits
|
||||||
|
without an operator clicking "Update" in the UI every time.
|
||||||
|
|
||||||
|
## Repository layout
|
||||||
|
|
||||||
|
Brencher looks at exactly one commit on one ref per environment. For a new
|
||||||
|
stack `my_stack`:
|
||||||
|
|
||||||
|
1. Push branch `feat/my_stack` (or whatever the team convention is) to a
|
||||||
|
Git repo listed in `remotes` of the config file.
|
||||||
|
2. Drop the repo in `gitea` or `github` so it's reachable through the same
|
||||||
|
remotes that other stacks use.
|
||||||
|
3. Make sure `my_stack/stack-compose.yml` and a Dockerfile (typically
|
||||||
|
`my_stack/Dockerfile`) exist at the path the config will point at.
|
||||||
|
|
||||||
|
## Config file: `backend/configs/<stack>.py`
|
||||||
|
|
||||||
|
The shape is fixed by `enironment.Environment` and the steps it pulls in.
|
||||||
|
Look at `backend/configs/hermes.py` for the canonical pattern. A new config
|
||||||
|
must:
|
||||||
|
|
||||||
|
- Build a `GitClone` with at least one remote whose `url` points to the repo
|
||||||
|
above.
|
||||||
|
- Build a `DockerSwarmCheck(stack_name="<stack>")` to introspect the
|
||||||
|
deployed service.
|
||||||
|
- Build **`GitUnmerge(clone, dockerSwarmCheck)`** and wrap it into
|
||||||
|
`SharedStateHolderInMemory(unmerge=unmerge)`. This is what makes
|
||||||
|
autodeploy work — `GitUnmerge` reads the `org.brencher.version` label
|
||||||
|
from the running swarm task and converts it into
|
||||||
|
`desired_branches`, so each polling cycle asks "is HEAD ≠ what's
|
||||||
|
deployed?" without any UI input.
|
||||||
|
- Wire a `CheckoutMerged(clone, desired_branches=state, push=False, …)`.
|
||||||
|
Push stays `False` for first-party stacks; set `True` only when you want
|
||||||
|
brencher to push auto-named branches back to origin.
|
||||||
|
- Build a `DockerComposeBuild` (or `DockerSwarmBuild` if a Swarmfile is
|
||||||
|
used) pointing at the compose path in the repo.
|
||||||
|
- Build a `DockerSwarmDeploy(wd=clone, buildDocker=…, stackChecker=…, …)`
|
||||||
|
with the same `stack_name`. Image tag is `auto-<short-sha>` driven by
|
||||||
|
`checkoutMerged.progress().version`.
|
||||||
|
- Optionally append a `SimpleLog(message={"userLinks": {...}})` for the
|
||||||
|
link to surface in the UI.
|
||||||
|
- Set `__all__` and export the `Environment` named after the stack id.
|
||||||
|
- Add it to `Environment.pipeline` in the canonical order:
|
||||||
|
`clone → state → checkoutMerged → dockerSwarmCheck → build → deploy →
|
||||||
|
optionals`. Build and deploy are explicit `DockerComposeBuild` and
|
||||||
|
`DockerSwarmDeploy` siblings; do not collapse them into one step.
|
||||||
|
|
||||||
|
If you skip the `GitUnmerge` line, `state.branches` will stay empty and
|
||||||
|
the stack will only deploy when an operator pushes a `branches` update
|
||||||
|
through the UI. Don't skip it; it's the difference between a self-driving
|
||||||
|
stack and a manual one. See `connectivity_tester.py` history for the bug
|
||||||
|
this caused.
|
||||||
|
|
||||||
|
## Verification checklist
|
||||||
|
|
||||||
|
- `python3 -c "from backend.configs.my_stack import my_stack"` works in
|
||||||
|
the brencher container.
|
||||||
|
- `PROFILES="my_stack" python3 backend/app.py` boots and the UI renders a
|
||||||
|
row for `my_stack` with non-empty branches (from `GitUnmerge`,
|
||||||
|
pointing at whatever image is currently deployed).
|
||||||
|
- Push to the configured branch, wait one full polling cycle
|
||||||
|
(~`RESET_INTERVAL` = 180s, plus the next pipeline tick), then confirm
|
||||||
|
the service was redeployed with a new `org.brencher.version` label.
|
||||||
|
- No UI `environment_update` was issued in between.
|
||||||
|
|
||||||
|
## Common foot-guns
|
||||||
|
|
||||||
|
- `dockerfile:` path in `stack-compose.yml` is interpreted relative to the
|
||||||
|
compose file's directory. The compose file and the Dockerfile must
|
||||||
|
live side-by-side; use `dockerfile: Dockerfile`, not
|
||||||
|
`dockerfile: <relative-path>`.
|
||||||
|
- Removing the `name:` key from the top of `stack-compose.yml` is fine
|
||||||
|
for `docker stack deploy` — the stack name comes from the CLI option
|
||||||
|
brencher sets.
|
||||||
|
- `EXTRA_ENDPOINTS` and friends are env vars; if you reference them in
|
||||||
|
compose, define them in the `envs=lambda: {...}` of the
|
||||||
|
`DockerComposeBuild` and `DockerSwarmDeploy`. `substitute` uses
|
||||||
|
`env.get(...)` for deploys but `env[...]` (raises) for builds, so an
|
||||||
|
unlisted variable kills the build but quietly produces an empty string
|
||||||
|
in the deploy.
|
||||||
|
- Compose files must not assume Docker networks that don't exist. Use
|
||||||
|
either an `external: true` net that already exists in Swarm, drop
|
||||||
|
the `networks:` block entirely, or `driver: overlay` for a
|
||||||
|
stack-private net.
|
||||||
|
|
||||||
|
## Tracking
|
||||||
|
|
||||||
|
When you add a stack, also:
|
||||||
|
|
||||||
|
- Open a tracking issue in `admin/brencher` titled
|
||||||
|
`[ready-to-test] <stack>: …` with `state=` from your
|
||||||
|
`GitUnmerge`-derived branches and what URL/port the service exposes.
|
||||||
|
- Add the stack id to the `PROFILES` env var in the brencher stack
|
||||||
|
compose (`docker_stack` / Swarm declarative) so it gets picked up on
|
||||||
|
next rollout. The admin overlay is where this lives.
|
||||||
|
|
||||||
|
## Build delegation pattern (Actions)
|
||||||
|
|
||||||
|
Brencher does not run docker build or docker push itself. It dispatches a Gitea
|
||||||
|
Actions workflow via `POST /api/v1/repos/{owner}/{repo}/actions/workflows/{file}/dispatches`,
|
||||||
|
waits for the run to complete, then runs `docker stack deploy`.
|
||||||
|
|
||||||
|
Use `steps.actions.GiteaActionsTrigger` and `steps.actions.GiteaActionsAwait`
|
||||||
|
in the stack config, set `buildDocker=None` on `DockerSwarmDeploy`, and let Swarm
|
||||||
|
resolve and pull the image on target nodes during deploy. Credentials must be
|
||||||
|
available to the deploy path and the compose image must point to a registry the
|
||||||
|
runner can push to (e.g. Gitea Container Registry `gitea.rudolf.keenetic.link/<owner>/<repo>`).
|
||||||
@@ -33,7 +33,7 @@ docker service update --secret-rm brencher-secrets brencher_brencher-backend
|
|||||||
docker service update --secret-rm brencher-secrets brencher2_brencher-backend
|
docker service update --secret-rm brencher-secrets brencher2_brencher-backend
|
||||||
docker secret rm brencher-secrets
|
docker secret rm brencher-secrets
|
||||||
|
|
||||||
printf "GIT_USERNAME=git\nGIT_PASSWORD=TODO\n" | \
|
printf "GIT_USERNAME=git\nGIT_PASSWORD=TODO\nGITEA_TOKEN=TODO\n" | \
|
||||||
docker secret create brencher-secrets -
|
docker secret create brencher-secrets -
|
||||||
|
|
||||||
docker service update --secret-add brencher-secrets brencher_brencher-backend
|
docker service update --secret-add brencher-secrets brencher_brencher-backend
|
||||||
|
|||||||
@@ -17,3 +17,6 @@
|
|||||||
state: str # 'Active' or 'Pause'
|
state: str # 'Active' or 'Pause'
|
||||||
pipeline: Dict[str, Any]
|
pipeline: Dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+13
-4
@@ -48,21 +48,30 @@ class App:
|
|||||||
"name": r.name,
|
"name": r.name,
|
||||||
"status": [str(result), stack],
|
"status": [str(result), stack],
|
||||||
"error": True,
|
"error": True,
|
||||||
"is_running": True,
|
"is_running": False,
|
||||||
})
|
})
|
||||||
else:
|
else:
|
||||||
pipeline_state.append({
|
step_state = {
|
||||||
"name": r.name,
|
"name": r.name,
|
||||||
"status": result,
|
"status": result,
|
||||||
"is_running": False,
|
"is_running": False,
|
||||||
})
|
}
|
||||||
|
step_errors = getattr(r, "errors", [])
|
||||||
|
if step_errors:
|
||||||
|
step_state["status"] = {"result": result, "errors": step_errors}
|
||||||
|
step_state["error"] = True
|
||||||
|
step_warnings = getattr(r, "warnings", [])
|
||||||
|
if step_warnings and not step_errors:
|
||||||
|
step_state["status"] = {"result": result, "warnings": step_warnings}
|
||||||
|
step_state["warning"] = True
|
||||||
|
pipeline_state.append(step_state)
|
||||||
except BaseException as e:
|
except BaseException as e:
|
||||||
stack = traceback.format_exception(type(e), e, e.__traceback__)
|
stack = traceback.format_exception(type(e), e, e.__traceback__)
|
||||||
pipeline_state.append({
|
pipeline_state.append({
|
||||||
"name": r.name,
|
"name": r.name,
|
||||||
"status": [str(e), stack],
|
"status": [str(e), stack],
|
||||||
"error": True,
|
"error": True,
|
||||||
"is_running": True,
|
"is_running": False,
|
||||||
})
|
})
|
||||||
env_dtos[env.id] = {'id': env.id }
|
env_dtos[env.id] = {'id': env.id }
|
||||||
env_dtos[env.id]['pipeline'] = pipeline_state
|
env_dtos[env.id]['pipeline'] = pipeline_state
|
||||||
|
|||||||
@@ -5,7 +5,10 @@ from steps.docker import DockerComposeBuild, DockerSwarmCheck, DockerSwarmDeploy
|
|||||||
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
||||||
from steps.shared_state import SharedStateHolderInMemory
|
from steps.shared_state import SharedStateHolderInMemory
|
||||||
|
|
||||||
clone = GitClone(url="https://github.com/rudolf1/brencher.git")
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "github", "url": "https://github.com/rudolf1/brencher.git"},
|
||||||
|
{"name": "gitea_hermes", "url": "https://gitea.rudolf.keenetic.link/hermes/brencher"},
|
||||||
|
])
|
||||||
|
|
||||||
dockerSwarmCheck = DockerSwarmCheck(
|
dockerSwarmCheck = DockerSwarmCheck(
|
||||||
stack_name="brencher",
|
stack_name="brencher",
|
||||||
|
|||||||
@@ -21,7 +21,11 @@ def checkPingF(obj: Any) -> None:
|
|||||||
raise Exception(f"brencher2 check failed for: {v}")
|
raise Exception(f"brencher2 check failed for: {v}")
|
||||||
|
|
||||||
|
|
||||||
clone = GitClone(url="https://github.com/rudolf1/brencher.git")
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "github", "url": "https://github.com/rudolf1/brencher.git"},
|
||||||
|
{"name": "gitea_admin", "url": "https://gitea.rudolf.keenetic.link/admin/brencher"},
|
||||||
|
{"name": "gitea_hermes", "url": "https://gitea.rudolf.keenetic.link/hermes/brencher"},
|
||||||
|
])
|
||||||
|
|
||||||
dockerSwarmCheck = DockerSwarmCheck(
|
dockerSwarmCheck = DockerSwarmCheck(
|
||||||
stack_name="brencher2",
|
stack_name="brencher2",
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import os
|
||||||
|
|
||||||
|
from enironment import Environment
|
||||||
|
from steps.actions import GiteaActionsAwait, GiteaActionsTrigger
|
||||||
|
from steps.checks import SimpleLog
|
||||||
|
from steps.docker import DockerSwarmCheck, DockerSwarmDeploy
|
||||||
|
from steps.git import CheckoutMerged, GitClone, GitUnmerge
|
||||||
|
from steps.shared_state import SharedStateHolderInMemory
|
||||||
|
|
||||||
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "gitea_hermes", "url": "https://gitea.rudolf.keenetic.link/hermes/ansible"},
|
||||||
|
{"name": "gitea_admin", "url": "https://gitea.rudolf.keenetic.link/admin/ansible"},
|
||||||
|
],
|
||||||
|
credEnvPrefix="GITEA",
|
||||||
|
)
|
||||||
|
|
||||||
|
dockerSwarmCheck = DockerSwarmCheck(stack_name="connectivity_tester")
|
||||||
|
|
||||||
|
unmerge = GitUnmerge(clone, dockerSwarmCheck)
|
||||||
|
state = SharedStateHolderInMemory(unmerge=unmerge)
|
||||||
|
|
||||||
|
checkoutMerged = CheckoutMerged(
|
||||||
|
clone,
|
||||||
|
desired_branches=state,
|
||||||
|
push="gitea_admin",
|
||||||
|
git_user_email="rudolfss13@gmail.com",
|
||||||
|
git_user_name="brencher_bot",
|
||||||
|
)
|
||||||
|
|
||||||
|
GITEA_API = os.environ.get("GITEA_API", "https://gitea.rudolf.keenetic.link/api/v1")
|
||||||
|
GITEA_TOKEN = os.environ.get("GITEA_TOKEN", "")
|
||||||
|
|
||||||
|
WORKFLOW_OWNER = "admin"
|
||||||
|
WORKFLOW_REPO = "ansible"
|
||||||
|
WORKFLOW_FILE = "release.yml"
|
||||||
|
|
||||||
|
def _inputs() -> dict:
|
||||||
|
return {"tag": "auto-" + checkoutMerged.progress().version}
|
||||||
|
|
||||||
|
trigger_build = GiteaActionsTrigger(
|
||||||
|
api_base=GITEA_API,
|
||||||
|
owner=WORKFLOW_OWNER,
|
||||||
|
repo=WORKFLOW_REPO,
|
||||||
|
workflow_file=WORKFLOW_FILE,
|
||||||
|
ref=lambda: checkoutMerged.progress().remote_branch_name or "master",
|
||||||
|
token=GITEA_TOKEN,
|
||||||
|
inputs=_inputs,
|
||||||
|
wd=checkoutMerged,
|
||||||
|
)
|
||||||
|
|
||||||
|
await_build = GiteaActionsAwait(
|
||||||
|
api_base=GITEA_API,
|
||||||
|
owner=WORKFLOW_OWNER,
|
||||||
|
repo=WORKFLOW_REPO,
|
||||||
|
token=GITEA_TOKEN,
|
||||||
|
run=lambda: trigger_build.progress(),
|
||||||
|
)
|
||||||
|
|
||||||
|
deployDocker = DockerSwarmDeploy(
|
||||||
|
wd=clone,
|
||||||
|
buildDocker=None,
|
||||||
|
stackChecker=dockerSwarmCheck,
|
||||||
|
envs=lambda: {
|
||||||
|
"version": "auto-" + checkoutMerged.progress().version,
|
||||||
|
"registry_owner": "admin",
|
||||||
|
},
|
||||||
|
stack_name="connectivity_tester",
|
||||||
|
docker_compose_path="connectivity_tester/stack-compose.yml",
|
||||||
|
)
|
||||||
|
|
||||||
|
logUrls = SimpleLog(message={
|
||||||
|
"userLinks": {
|
||||||
|
"Connectivity tester": "http://connectivity-tester.keenetic.link:8765/",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
__all__ = ["connectivity_tester"]
|
||||||
|
connectivity_tester = Environment(
|
||||||
|
id="connectivity_tester",
|
||||||
|
state=state,
|
||||||
|
pipeline=[
|
||||||
|
clone,
|
||||||
|
state,
|
||||||
|
checkoutMerged,
|
||||||
|
dockerSwarmCheck,
|
||||||
|
trigger_build,
|
||||||
|
await_build,
|
||||||
|
deployDocker,
|
||||||
|
logUrls,
|
||||||
|
],
|
||||||
|
)
|
||||||
@@ -4,7 +4,28 @@ from steps.docker import DockerSwarmCheck, DockerSwarmDeploy
|
|||||||
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
||||||
from steps.shared_state import SharedStateHolderInMemory
|
from steps.shared_state import SharedStateHolderInMemory
|
||||||
|
|
||||||
clone = GitClone(url="https://github.com/rudolf1/uber_backup.git", branchNamePrefix="ansible")
|
# Dual-remote clone for the ansible mirror (the deploy target, not brencher itself).
|
||||||
|
# - gitea_hermes is where the feature branch lives (hermes/ansible:*)
|
||||||
|
# - gitea_admin is the live-deploy source (where brencher-bot reads compose files from)
|
||||||
|
#
|
||||||
|
# Why not github? github.com is unreachable from the brencher container -- the
|
||||||
|
# proxy returns HTTP 403 on CONNECT tunnel, so the URL would always fail to
|
||||||
|
# fetch. See backend/configs/docker_socket_proxy.py for the same migration.
|
||||||
|
#
|
||||||
|
# Why drop branchNamePrefix? GitClone only applies its prefix refspec to a
|
||||||
|
# remote named "origin" (backend/steps/git.py ~L104); neither remote here is
|
||||||
|
# named "origin", so the prefix would be a silent no-op. Both remotes fetch
|
||||||
|
# their full refset instead.
|
||||||
|
#
|
||||||
|
# Why two remotes? The deploy step (DockerSwarmDeploy) checks out a specific
|
||||||
|
# branch and uses the resulting checkout as wd for the compose path. With
|
||||||
|
# gitea_hermes as primary, feature branches opened in the fork are picked up;
|
||||||
|
# gitea_admin provides the live-deploy source as a fallback / for cross-fork
|
||||||
|
# PRs. This matches the form in backend/configs/brencher.py after PR #3.
|
||||||
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "gitea_hermes", "url": "https://gitea.rudolf.keenetic.link/hermes/ansible"},
|
||||||
|
{"name": "gitea_admin", "url": "https://gitea.rudolf.keenetic.link/admin/ansible"},
|
||||||
|
])
|
||||||
|
|
||||||
dockerSwarmCheck = DockerSwarmCheck(
|
dockerSwarmCheck = DockerSwarmCheck(
|
||||||
stack_name="gitea",
|
stack_name="gitea",
|
||||||
|
|||||||
@@ -4,7 +4,10 @@ from steps.docker import DockerComposeBuild, DockerSwarmCheck, DockerSwarmDeploy
|
|||||||
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
||||||
from steps.shared_state import SharedStateHolderInMemory
|
from steps.shared_state import SharedStateHolderInMemory
|
||||||
|
|
||||||
clone = GitClone(url="https://github.com/rudolf1/uber_backup.git", branchNamePrefix="immoscout")
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "gitea_hermes", "url": "https://gitea.rudolf.keenetic.link/hermes/mcps"},
|
||||||
|
{"name": "gitea_admin", "url": "https://gitea.rudolf.keenetic.link/admin/mcps"},
|
||||||
|
])
|
||||||
|
|
||||||
dockerSwarmCheck = DockerSwarmCheck(
|
dockerSwarmCheck = DockerSwarmCheck(
|
||||||
stack_name="gmail_mcp",
|
stack_name="gmail_mcp",
|
||||||
@@ -23,7 +26,7 @@ checkoutMerged = CheckoutMerged(clone,
|
|||||||
buildDocker = DockerComposeBuild(clone,
|
buildDocker = DockerComposeBuild(clone,
|
||||||
docker_repo_username="",
|
docker_repo_username="",
|
||||||
docker_repo_password="",
|
docker_repo_password="",
|
||||||
docker_compose_path="gmail-mcp-server/docker-compose.yml",
|
docker_compose_path="docker-compose.yml",
|
||||||
docker_repo_url="https://registry.rudolf.keenetic.link",
|
docker_repo_url="https://registry.rudolf.keenetic.link",
|
||||||
publish=False,
|
publish=False,
|
||||||
envs=lambda: {
|
envs=lambda: {
|
||||||
@@ -39,7 +42,7 @@ deployDocker = DockerSwarmDeploy(
|
|||||||
"version": "auto-" + checkoutMerged.progress().version,
|
"version": "auto-" + checkoutMerged.progress().version,
|
||||||
},
|
},
|
||||||
stack_name="gmail_mcp",
|
stack_name="gmail_mcp",
|
||||||
docker_compose_path="gmail-mcp-server/docker-compose.yml",
|
docker_compose_path="docker-compose.yml",
|
||||||
)
|
)
|
||||||
|
|
||||||
checkPing1 = UrlCheck(
|
checkPing1 = UrlCheck(
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
from enironment import Environment
|
from enironment import Environment
|
||||||
from steps.checks import SimpleLog, UrlCheck
|
from steps.checks import SimpleLog
|
||||||
from steps.docker import DockerSwarmCheck, DockerSwarmDeploy
|
from steps.docker import DockerSwarmCheck, DockerSwarmDeploy
|
||||||
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
||||||
from steps.shared_state import SharedStateHolderInMemory
|
from steps.shared_state import SharedStateHolderInMemory
|
||||||
|
|
||||||
clone = GitClone(url="https://github.com/rudolf1/uber_backup.git", branchNamePrefix="ansible")
|
clone = GitClone(remotes=[
|
||||||
|
# {"name": "github", "url": "https://github.com/rudolf1/uber_backup.git", "prefix": "ansible"},
|
||||||
|
{"name": "gitea_hermes", "url": "https://gitea.rudolf.keenetic.link/hermes/ansible"},
|
||||||
|
{"name": "gitea_admin", "url": "https://gitea.rudolf.keenetic.link/admin/ansible"},
|
||||||
|
])
|
||||||
|
|
||||||
dockerSwarmCheck = DockerSwarmCheck(
|
dockerSwarmCheck = DockerSwarmCheck(
|
||||||
stack_name="hermes",
|
stack_name="hermes",
|
||||||
@@ -31,10 +35,10 @@ deployDocker = DockerSwarmDeploy(
|
|||||||
docker_compose_path="poc/hermes/stack-compose.yml",
|
docker_compose_path="poc/hermes/stack-compose.yml",
|
||||||
)
|
)
|
||||||
|
|
||||||
checkPing1 = UrlCheck(
|
# checkPing1 = UrlCheck(
|
||||||
url="http://100.70.193.97:8087/api/status",
|
# url="http://100.70.193.97:8087/api/status",
|
||||||
expected=lambda obj: obj['gateway_running'] == 'true' and obj['auth_required'] == 'true',
|
# expected=lambda obj: obj['gateway_running'] == 'true' and obj['auth_required'] == 'true',
|
||||||
)
|
# )
|
||||||
logUrls = SimpleLog(message={
|
logUrls = SimpleLog(message={
|
||||||
"userLinks": {
|
"userLinks": {
|
||||||
"App": "https://hermes.rudolf.keenetic.link",
|
"App": "https://hermes.rudolf.keenetic.link",
|
||||||
@@ -53,7 +57,7 @@ hermes = Environment(
|
|||||||
dockerSwarmCheck,
|
dockerSwarmCheck,
|
||||||
unmerge,
|
unmerge,
|
||||||
deployDocker,
|
deployDocker,
|
||||||
checkPing1,
|
# checkPing1,
|
||||||
logUrls
|
logUrls
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,14 +4,35 @@ from steps.docker import DockerComposeBuild, DockerSwarmCheck, DockerSwarmDeploy
|
|||||||
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
||||||
from steps.shared_state import SharedStateHolderInMemory
|
from steps.shared_state import SharedStateHolderInMemory
|
||||||
|
|
||||||
clone = GitClone(url="https://github.com/rudolf1/uber_backup.git", branchNamePrefix="ansible")
|
# Dual-remote clone for the ansible mirror (the deploy target, not brencher itself).
|
||||||
|
# - gitea_hermes is where the feature branch lives (hermes/ansible:*)
|
||||||
|
# - gitea_admin is the live-deploy source (where brencher-bot reads compose files from)
|
||||||
|
#
|
||||||
|
# Why not github? github.com is unreachable from the brencher container -- the
|
||||||
|
# proxy returns HTTP 403 on CONNECT tunnel, so the URL would always fail to
|
||||||
|
# fetch. See backend/configs/docker_socket_proxy.py for the same migration.
|
||||||
|
#
|
||||||
|
# Why drop branchNamePrefix? GitClone only applies its prefix refspec to a
|
||||||
|
# remote named "origin" (backend/steps/git.py ~L104); neither remote here is
|
||||||
|
# named "origin", so the prefix would be a silent no-op. Both remotes fetch
|
||||||
|
# their full refset instead.
|
||||||
|
#
|
||||||
|
# Why two remotes? The deploy step (DockerSwarmDeploy) checks out a specific
|
||||||
|
# branch and uses the resulting checkout as wd for the compose path. With
|
||||||
|
# gitea_hermes as primary, feature branches opened in the fork are picked up;
|
||||||
|
# gitea_admin provides the live-deploy source as a fallback / for cross-fork
|
||||||
|
# PRs. This matches the form in backend/configs/brencher.py after PR #3.
|
||||||
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "gitea_hermes", "url": "https://gitea.rudolf.keenetic.link/hermes/ansible"},
|
||||||
|
{"name": "gitea_admin", "url": "https://gitea.rudolf.keenetic.link/admin/ansible"},
|
||||||
|
])
|
||||||
|
|
||||||
dockerSwarmCheck = DockerSwarmCheck(
|
dockerSwarmCheck = DockerSwarmCheck(
|
||||||
stack_name="hermes_infra",
|
stack_name="hermes_infra",
|
||||||
)
|
)
|
||||||
unmerge = GitUnmerge(clone, dockerSwarmCheck)
|
unmerge = GitUnmerge(clone, dockerSwarmCheck)
|
||||||
|
|
||||||
state = SharedStateHolderInMemory(unmerge=None)
|
state = SharedStateHolderInMemory(unmerge=unmerge)
|
||||||
|
|
||||||
checkoutMerged = CheckoutMerged(clone,
|
checkoutMerged = CheckoutMerged(clone,
|
||||||
desired_branches=state,
|
desired_branches=state,
|
||||||
|
|||||||
@@ -4,7 +4,28 @@ from steps.docker import DockerSwarmCheck, DockerSwarmDeploy
|
|||||||
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
||||||
from steps.shared_state import SharedStateHolderInMemory
|
from steps.shared_state import SharedStateHolderInMemory
|
||||||
|
|
||||||
clone = GitClone(url="https://github.com/rudolf1/uber_backup.git", branchNamePrefix="ansible")
|
# Dual-remote clone for the ansible mirror (the deploy target, not brencher itself).
|
||||||
|
# - gitea_hermes is where the feature branch lives (hermes/ansible:*)
|
||||||
|
# - gitea_admin is the live-deploy source (where brencher-bot reads compose files from)
|
||||||
|
#
|
||||||
|
# Why not github? github.com is unreachable from the brencher container -- the
|
||||||
|
# proxy returns HTTP 403 on CONNECT tunnel, so the URL would always fail to
|
||||||
|
# fetch. See backend/configs/docker_socket_proxy.py for the same migration.
|
||||||
|
#
|
||||||
|
# Why drop branchNamePrefix? GitClone only applies its prefix refspec to a
|
||||||
|
# remote named "origin" (backend/steps/git.py ~L104); neither remote here is
|
||||||
|
# named "origin", so the prefix would be a silent no-op. Both remotes fetch
|
||||||
|
# their full refset instead.
|
||||||
|
#
|
||||||
|
# Why two remotes? The deploy step (DockerSwarmDeploy) checks out a specific
|
||||||
|
# branch and uses the resulting checkout as wd for the compose path. With
|
||||||
|
# gitea_hermes as primary, feature branches opened in the fork are picked up;
|
||||||
|
# gitea_admin provides the live-deploy source as a fallback / for cross-fork
|
||||||
|
# PRs. This matches the form in backend/configs/brencher.py after PR #3.
|
||||||
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "gitea_hermes", "url": "https://gitea.rudolf.keenetic.link/hermes/ansible"},
|
||||||
|
{"name": "gitea_admin", "url": "https://gitea.rudolf.keenetic.link/admin/ansible"},
|
||||||
|
])
|
||||||
|
|
||||||
dockerSwarmCheck = DockerSwarmCheck(
|
dockerSwarmCheck = DockerSwarmCheck(
|
||||||
stack_name="immich",
|
stack_name="immich",
|
||||||
|
|||||||
@@ -3,7 +3,11 @@ from steps.docker import DockerComposeBuild, DockerSwarmCheck, DockerSwarmDeploy
|
|||||||
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
from steps.git import GitClone, CheckoutMerged, GitUnmerge
|
||||||
from steps.shared_state import SharedStateHolderInMemory
|
from steps.shared_state import SharedStateHolderInMemory
|
||||||
|
|
||||||
clone = GitClone(url="https://github.com/rudolf1/reverseproxy.git")
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "github", "url": "https://github.com/rudolf1/reverseproxy.git"},
|
||||||
|
{"name": "gitea_admin", "url": "https://gitea.rudolf.keenetic.link/admin/reverseproxy"},
|
||||||
|
{"name": "gitea_hermes", "url": "https://gitea.rudolf.keenetic.link/hermes/reverseproxy"},
|
||||||
|
])
|
||||||
|
|
||||||
dockerSwarmCheck = DockerSwarmCheck(
|
dockerSwarmCheck = DockerSwarmCheck(
|
||||||
stack_name="torrserv_proxy",
|
stack_name="torrserv_proxy",
|
||||||
|
|||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any, Callable, Dict, Optional, Union
|
||||||
|
|
||||||
|
from enironment import AbstractStep
|
||||||
|
from steps.git import CheckoutMerged
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class GiteaActionsRun:
|
||||||
|
run_id: int
|
||||||
|
status: str
|
||||||
|
conclusion: Optional[str]
|
||||||
|
html_url: str
|
||||||
|
|
||||||
|
|
||||||
|
InputsSource = Union[Dict[str, str], Callable[[], Dict[str, str]], None]
|
||||||
|
RefSource = Union[str, Callable[[], Optional[str]], None]
|
||||||
|
|
||||||
|
|
||||||
|
class GiteaActionsTrigger(AbstractStep[GiteaActionsRun]):
|
||||||
|
"""Trigger a Gitea Actions workflow via the dispatches API."""
|
||||||
|
|
||||||
|
def __init__(self,
|
||||||
|
api_base: str,
|
||||||
|
owner: str,
|
||||||
|
repo: str,
|
||||||
|
workflow_file: str,
|
||||||
|
ref: RefSource,
|
||||||
|
token: str,
|
||||||
|
inputs: InputsSource = None,
|
||||||
|
wd: Optional[CheckoutMerged] = None,
|
||||||
|
poll_timeout_sec: int = 1800,
|
||||||
|
poll_interval_sec: int = 10,
|
||||||
|
**kwargs: Any) -> None:
|
||||||
|
super().__init__(**kwargs)
|
||||||
|
self.api_base = api_base.rstrip("/")
|
||||||
|
self.owner = owner
|
||||||
|
self.repo = repo
|
||||||
|
self.workflow_file = workflow_file
|
||||||
|
self.ref = ref
|
||||||
|
self.token = token
|
||||||
|
self.inputs = inputs
|
||||||
|
self.wd = wd
|
||||||
|
self.poll_timeout_sec = poll_timeout_sec
|
||||||
|
self.poll_interval_sec = poll_interval_sec
|
||||||
|
|
||||||
|
def _http(self, method: str, url: str, body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||||
|
data = None
|
||||||
|
headers = {"Authorization": f"token {self.token}", "Accept": "application/json"}
|
||||||
|
if body is not None:
|
||||||
|
data = json.dumps(body).encode()
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||||
|
with urllib.request.urlopen(req, timeout=30) as r:
|
||||||
|
body_bytes = r.read()
|
||||||
|
if not body_bytes or r.status == 204:
|
||||||
|
return {}
|
||||||
|
return json.loads(body_bytes.decode())
|
||||||
|
|
||||||
|
def _list_recent_runs(self) -> Optional[GiteaActionsRun]:
|
||||||
|
url = f"{self.api_base}/repos/{self.owner}/{self.repo}/actions/runs?limit=1"
|
||||||
|
try:
|
||||||
|
data = self._http("GET", url)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
logger.error("list runs failed: %s", e)
|
||||||
|
return None
|
||||||
|
items = data.get("workflow_runs") or []
|
||||||
|
if not items:
|
||||||
|
return None
|
||||||
|
r = items[0]
|
||||||
|
return GiteaActionsRun(
|
||||||
|
run_id=r["id"],
|
||||||
|
status=r.get("status", ""),
|
||||||
|
conclusion=r.get("conclusion"),
|
||||||
|
html_url=r.get("html_url", ""),
|
||||||
|
)
|
||||||
|
|
||||||
|
def progress(self) -> GiteaActionsRun:
|
||||||
|
latest = self._list_recent_runs()
|
||||||
|
resolved_inputs: Dict[str, str] = {}
|
||||||
|
if callable(self.inputs):
|
||||||
|
resolved_inputs = self.inputs() or {}
|
||||||
|
elif isinstance(self.inputs, dict):
|
||||||
|
resolved_inputs = self.inputs
|
||||||
|
ref = self.ref() if callable(self.ref) else self.ref
|
||||||
|
body: Dict[str, Any] = {"ref": ref}
|
||||||
|
if resolved_inputs:
|
||||||
|
body["inputs"] = resolved_inputs
|
||||||
|
url = (
|
||||||
|
f"{self.api_base}/repos/{self.owner}/{self.repo}"
|
||||||
|
f"/actions/workflows/{self.workflow_file}/dispatches"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
self._http("POST", url, body=body)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
if e.code != 500:
|
||||||
|
raise
|
||||||
|
raise RuntimeError(
|
||||||
|
"POST /dispatches returned 500 (gitea-side bug on this instance). "
|
||||||
|
"Workaround: trigger the workflow manually by pushing a tag matching "
|
||||||
|
f"the workflow's `on.push.tags` filter, e.g. "
|
||||||
|
f"`git push <repo> HEAD:refs/tags/auto-<sha>`. "
|
||||||
|
f"Requested workflow: {self.owner}/{self.repo}/{self.workflow_file}@{ref}"
|
||||||
|
) from e
|
||||||
|
deadline = time.time() + self.poll_timeout_sec
|
||||||
|
while time.time() < deadline:
|
||||||
|
current = self._list_recent_runs()
|
||||||
|
if current is None or (latest is not None and current.run_id == latest.run_id):
|
||||||
|
time.sleep(self.poll_interval_sec)
|
||||||
|
continue
|
||||||
|
return current
|
||||||
|
raise TimeoutError(
|
||||||
|
f"Gitea Actions did not pick up a new run within {self.poll_timeout_sec}s"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class GiteaActionsAwait(AbstractStep[GiteaActionsRun]):
|
||||||
|
"""Wait for a previously-triggered Gitea Actions run to complete."""
|
||||||
|
|
||||||
|
def __init__(self,
|
||||||
|
api_base: str,
|
||||||
|
owner: str,
|
||||||
|
repo: str,
|
||||||
|
token: str,
|
||||||
|
run: Callable[[], GiteaActionsRun],
|
||||||
|
poll_timeout_sec: int = 1800,
|
||||||
|
poll_interval_sec: int = 10,
|
||||||
|
**kwargs: Any) -> None:
|
||||||
|
super().__init__(**kwargs)
|
||||||
|
self.api_base = api_base.rstrip("/")
|
||||||
|
self.owner = owner
|
||||||
|
self.repo = repo
|
||||||
|
self.token = token
|
||||||
|
self._run = run
|
||||||
|
self.poll_timeout_sec = poll_timeout_sec
|
||||||
|
self.poll_interval_sec = poll_interval_sec
|
||||||
|
|
||||||
|
def _http(self, method: str, url: str) -> Dict[str, Any]:
|
||||||
|
headers = {"Authorization": f"token {self.token}", "Accept": "application/json"}
|
||||||
|
req = urllib.request.Request(url, headers=headers, method=method)
|
||||||
|
with urllib.request.urlopen(req, timeout=30) as r:
|
||||||
|
return json.loads(r.read().decode())
|
||||||
|
|
||||||
|
def progress(self) -> GiteaActionsRun:
|
||||||
|
run = self._run()
|
||||||
|
deadline = time.time() + self.poll_timeout_sec
|
||||||
|
while time.time() < deadline:
|
||||||
|
data = self._http(
|
||||||
|
"GET",
|
||||||
|
f"{self.api_base}/repos/{self.owner}/{self.repo}/actions/runs/{run.run_id}",
|
||||||
|
)
|
||||||
|
status = data.get("status", "")
|
||||||
|
conclusion = data.get("conclusion")
|
||||||
|
if status == "completed":
|
||||||
|
if conclusion != "success":
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Gitea Actions run {run.run_id} concluded with {conclusion}: "
|
||||||
|
f"{run.html_url}"
|
||||||
|
)
|
||||||
|
return GiteaActionsRun(
|
||||||
|
run_id=run.run_id,
|
||||||
|
status=status,
|
||||||
|
conclusion=conclusion,
|
||||||
|
html_url=run.html_url,
|
||||||
|
)
|
||||||
|
time.sleep(self.poll_interval_sec)
|
||||||
|
raise TimeoutError(
|
||||||
|
f"Gitea Actions run {run.run_id} did not complete within {self.poll_timeout_sec}s"
|
||||||
|
)
|
||||||
+69
-3
@@ -1,3 +1,4 @@
|
|||||||
|
import hashlib
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
@@ -197,12 +198,39 @@ class DockerSwarmDeploy(AbstractStep[str]):
|
|||||||
content = f.read()
|
content = f.read()
|
||||||
content = re.sub(r'\$\{([^}]+)\}', lambda m: env.get(m.group(1), ""), content)
|
content = re.sub(r'\$\{([^}]+)\}', lambda m: env.get(m.group(1), ""), content)
|
||||||
compose = yaml.safe_load(content)
|
compose = yaml.safe_load(content)
|
||||||
|
version = env["version"]
|
||||||
|
if "configs" in compose:
|
||||||
|
sanitized_version = re.sub(r'[^a-zA-Z0-9_.-]', '_', version)
|
||||||
|
full_prefix = f"{self.stack_name}_"
|
||||||
|
|
||||||
|
def _config_full_name(base_name: str) -> str:
|
||||||
|
full = f"{full_prefix}{base_name}_{sanitized_version}"
|
||||||
|
if len(full) <= 64:
|
||||||
|
return f"{base_name}_{sanitized_version}"
|
||||||
|
return hashlib.sha256(full.encode("utf-8")).hexdigest()[:32]
|
||||||
|
|
||||||
|
config_names = {
|
||||||
|
name: _config_full_name(name)
|
||||||
|
for name in compose["configs"]
|
||||||
|
}
|
||||||
|
compose["configs"] = {
|
||||||
|
config_names.get(name, name): config
|
||||||
|
for name, config in compose["configs"].items()
|
||||||
|
}
|
||||||
|
for service in compose.get("services", {}).values():
|
||||||
|
for config in service.get("configs", []):
|
||||||
|
if isinstance(config, str):
|
||||||
|
config_index = service["configs"].index(config)
|
||||||
|
service["configs"][config_index] = config_names.get(config, config)
|
||||||
|
elif isinstance(config, dict) and "source" in config:
|
||||||
|
config["source"] = config_names.get(config["source"], config["source"])
|
||||||
if "services" in compose:
|
if "services" in compose:
|
||||||
for svc in compose["services"].values():
|
for svc in compose["services"].values():
|
||||||
if "build" in svc:
|
if "build" in svc:
|
||||||
del svc["build"]
|
del svc["build"]
|
||||||
svc["labels"] = {"org.brencher.version": env["version"]}
|
svc["labels"] = {"org.brencher.version": env["version"]}
|
||||||
del env["version"]
|
del env["version"]
|
||||||
|
env.pop("registry_owner", None)
|
||||||
merge_dicts(compose, env)
|
merge_dicts(compose, env)
|
||||||
# logger.info(f"Final compose: {compose}")
|
# logger.info(f"Final compose: {compose}")
|
||||||
content = yaml.safe_dump(compose)
|
content = yaml.safe_dump(compose)
|
||||||
@@ -268,6 +296,8 @@ class DockerSwarmDeploy(AbstractStep[str]):
|
|||||||
# Deploy stack to Docker Swarm
|
# Deploy stack to Docker Swarm
|
||||||
cmd = [
|
cmd = [
|
||||||
"docker", "stack", "deploy",
|
"docker", "stack", "deploy",
|
||||||
|
"--with-registry-auth",
|
||||||
|
"--detach=false",
|
||||||
"--prune",
|
"--prune",
|
||||||
"-c", tmp_compose_path,
|
"-c", tmp_compose_path,
|
||||||
self.stack_name
|
self.stack_name
|
||||||
@@ -282,9 +312,24 @@ class DockerSwarmDeploy(AbstractStep[str]):
|
|||||||
result = subprocess.run(cmd, capture_output=True, text=True, cwd=os.path.dirname(tmp_compose_path))
|
result = subprocess.run(cmd, capture_output=True, text=True, cwd=os.path.dirname(tmp_compose_path))
|
||||||
#, env=swarmEnv)
|
#, env=swarmEnv)
|
||||||
os.remove(tmp_compose_path)
|
os.remove(tmp_compose_path)
|
||||||
if result.returncode != 0:
|
logger.info(f"docker stack deploy stdout: {result.stdout or '<empty>'}")
|
||||||
logger.error(f"Stack deploy failed: {result.stderr}")
|
logger.info(f"docker stack deploy stderr: {result.stderr or '<empty>'}")
|
||||||
raise RuntimeError(f"Stack deploy failed: {result.stderr}")
|
stderr_lower = result.stderr.lower()
|
||||||
|
docker_error_markers = (
|
||||||
|
"failed to ",
|
||||||
|
"error response from daemon",
|
||||||
|
"rpc error",
|
||||||
|
"denied",
|
||||||
|
"no such image",
|
||||||
|
)
|
||||||
|
if result.returncode != 0 or any(marker in stderr_lower for marker in docker_error_markers):
|
||||||
|
deploy_output = (
|
||||||
|
f"exit code: {result.returncode}\n"
|
||||||
|
f"stdout:\n{result.stdout or '<empty>'}\n"
|
||||||
|
f"stderr:\n{result.stderr or '<empty>'}"
|
||||||
|
)
|
||||||
|
logger.error(f"Stack deploy failed:\n{deploy_output}")
|
||||||
|
raise RuntimeError(f"Stack deploy failed:\n{deploy_output}")
|
||||||
logger.info(f"Stack deployed successfully: {result.stdout}")
|
logger.info(f"Stack deployed successfully: {result.stdout}")
|
||||||
|
|
||||||
# Check health of all deployed services
|
# Check health of all deployed services
|
||||||
@@ -308,4 +353,25 @@ class DockerSwarmDeploy(AbstractStep[str]):
|
|||||||
if not_running:
|
if not_running:
|
||||||
raise BaseException(f"Services not started yet: {', '.join(not_running)}")
|
raise BaseException(f"Services not started yet: {', '.join(not_running)}")
|
||||||
|
|
||||||
|
version_mismatches = []
|
||||||
|
for svc_name, svc in expected_services.items():
|
||||||
|
full_svc_name = f"{self.stack_name}_{svc_name}"
|
||||||
|
services_list = client.services.list(filters={"name": full_svc_name})
|
||||||
|
if not services_list:
|
||||||
|
continue
|
||||||
|
service_labels = services_list[0].attrs.get("Spec", {}).get("TaskTemplate", {}).get("ContainerSpec", {}).get("Labels", {})
|
||||||
|
expected_version = svc.get("labels", {}).get("org.brencher.version")
|
||||||
|
actual_version = service_labels.get("org.brencher.version")
|
||||||
|
if expected_version != actual_version:
|
||||||
|
version_mismatches.append(
|
||||||
|
f"{full_svc_name} expected version {expected_version}, got {actual_version}"
|
||||||
|
)
|
||||||
|
update_status = services_list[0].attrs.get("UpdateStatus", {})
|
||||||
|
if update_status.get("State") in {"paused", "rollback_paused", "rollback_started"}:
|
||||||
|
version_mismatches.append(
|
||||||
|
f"{full_svc_name} Swarm update {update_status.get('State')}: {update_status.get('Message', '')}"
|
||||||
|
)
|
||||||
|
if version_mismatches:
|
||||||
|
raise RuntimeError(f"Deployment did not apply requested versions: {'; '.join(version_mismatches)}")
|
||||||
|
|
||||||
return f"Stack deployed successfully: {result.stdout}"
|
return f"Stack deployed successfully: {result.stdout}"
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from typing import Any, Callable, Dict
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
from enironment import AbstractStep
|
||||||
|
from steps.git import GitClone
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class DockerComposePull(AbstractStep[Dict[str, str]]):
|
||||||
|
"""Pull images referenced by a docker-compose file from a remote registry."""
|
||||||
|
|
||||||
|
def __init__(self,
|
||||||
|
wd: GitClone,
|
||||||
|
docker_compose_path: str,
|
||||||
|
envs: Callable[[], Dict[str, Any]],
|
||||||
|
**kwargs: Any) -> None:
|
||||||
|
super().__init__(**kwargs)
|
||||||
|
self.wd = wd
|
||||||
|
self.envs = envs
|
||||||
|
self.docker_compose_path = docker_compose_path
|
||||||
|
|
||||||
|
def progress(self) -> Dict[str, str]:
|
||||||
|
env = self.envs()
|
||||||
|
compose_path = os.path.join(self.wd.progress(), self.docker_compose_path)
|
||||||
|
with open(compose_path, "r") as f:
|
||||||
|
content = f.read()
|
||||||
|
content = re.sub(r"\$\{([^}]+)\}", lambda m: env.get(m.group(1), ""), content)
|
||||||
|
compose = yaml.safe_load(content)
|
||||||
|
for svc in compose.get("services", {}).values():
|
||||||
|
if "build" in svc:
|
||||||
|
del svc["build"]
|
||||||
|
tmp_path = compose_path + ".pull.yml"
|
||||||
|
with open(tmp_path, "w") as f:
|
||||||
|
yaml.safe_dump(compose, f)
|
||||||
|
try:
|
||||||
|
subprocess.run(
|
||||||
|
["docker", "compose", "-f", tmp_path, "pull"],
|
||||||
|
check=True,
|
||||||
|
cwd=self.wd.progress(),
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
os.unlink(tmp_path)
|
||||||
|
return {name: svc.get("image", "") for name, svc in compose.get("services", {}).items()}
|
||||||
+149
-54
@@ -13,17 +13,65 @@ from git.objects import Commit
|
|||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
AUTO_BRANCH_PREFIX = "auto-"
|
||||||
|
|
||||||
|
|
||||||
class GitClone(AbstractStep[str]):
|
class GitClone(AbstractStep[str]):
|
||||||
def __init__(self, url: str, repo_path: str | None = None,
|
def __init__(self,
|
||||||
branchNamePrefix: str = "", credEnvPrefix: str = "GIT",
|
url: str | List[str] | None = None,
|
||||||
|
remotes: List[Dict[str, str]] | None = None,
|
||||||
|
repo_path: str | None = None,
|
||||||
|
branchNamePrefix: str = "",
|
||||||
|
credEnvPrefix: str = "GIT",
|
||||||
**kwargs: Any):
|
**kwargs: Any):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
self.url = url
|
# `remotes` is the explicit form: a list of {"name": "...", "url": "..."}.
|
||||||
|
# `url` is kept as a shorthand: a single string becomes one remote named
|
||||||
|
# "origin"; a list of strings becomes remotes named "origin", "repo1",
|
||||||
|
# "repo2", ... (matches the behavior introduced by the "multiple remotes"
|
||||||
|
# change so existing positional-list callers keep working).
|
||||||
|
if remotes is not None and url is not None:
|
||||||
|
raise ValueError("Pass either 'url' or 'remotes', not both")
|
||||||
|
|
||||||
|
normalized: List[Dict[str, str]] = []
|
||||||
|
if remotes is not None:
|
||||||
|
seen: Set[str] = set()
|
||||||
|
for entry in remotes:
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
raise TypeError(
|
||||||
|
f"Each entry in 'remotes' must be a dict with 'name' and 'url', got {type(entry).__name__}"
|
||||||
|
)
|
||||||
|
name = entry.get("name")
|
||||||
|
url_value = entry.get("url")
|
||||||
|
if not name or not isinstance(name, str):
|
||||||
|
raise ValueError("Each remote requires a non-empty 'name' (string)")
|
||||||
|
if not url_value or not isinstance(url_value, str):
|
||||||
|
raise ValueError(f"Remote {name!r} requires a non-empty 'url' (string)")
|
||||||
|
if name in seen:
|
||||||
|
raise ValueError(f"Duplicate remote name: {name!r}")
|
||||||
|
seen.add(name)
|
||||||
|
normalized.append({"name": name, "url": url_value})
|
||||||
|
elif url is not None:
|
||||||
|
if isinstance(url, str):
|
||||||
|
raw = [url]
|
||||||
|
else:
|
||||||
|
raw = list(url)
|
||||||
|
for index, repository_url in enumerate(raw):
|
||||||
|
name = "origin" if index == 0 else f"repo{index}"
|
||||||
|
normalized.append({"name": name, "url": repository_url})
|
||||||
|
else:
|
||||||
|
raise ValueError("GitClone requires either 'url' or 'remotes'")
|
||||||
|
|
||||||
|
if len(normalized) == 0:
|
||||||
|
raise ValueError("At least one repository URL is required")
|
||||||
|
|
||||||
|
self.remotes = normalized
|
||||||
|
# Derived view used by repo_path keying and any introspection.
|
||||||
|
self.urls = [r["url"] for r in normalized]
|
||||||
self.repo_path = repo_path
|
self.repo_path = repo_path
|
||||||
self.branchNamePrefix = branchNamePrefix
|
self.branchNamePrefix = branchNamePrefix
|
||||||
self.credEnvPrefix = credEnvPrefix
|
self.credEnvPrefix = credEnvPrefix
|
||||||
|
self.errors: List[str] = []
|
||||||
|
|
||||||
def _get_auth_git_url(self, url: str) -> str:
|
def _get_auth_git_url(self, url: str) -> str:
|
||||||
username = os.getenv(f'{self.credEnvPrefix}_USERNAME')
|
username = os.getenv(f'{self.credEnvPrefix}_USERNAME')
|
||||||
@@ -36,33 +84,53 @@ class GitClone(AbstractStep[str]):
|
|||||||
return url
|
return url
|
||||||
|
|
||||||
def progress(self) -> str:
|
def progress(self) -> str:
|
||||||
repo_url = self.url
|
self.errors = []
|
||||||
|
|
||||||
self.repo_path = self.repo_path or os.path.join(tempfile.gettempdir(),
|
self.repo_path = self.repo_path or os.path.join(tempfile.gettempdir(),
|
||||||
f"{self.env.id}_{hashlib.sha1(repo_url.encode()).hexdigest()[:5]}")
|
f"{self.env.id}_{hashlib.sha1('|'.join(self.urls).encode()).hexdigest()[:5]}")
|
||||||
logger.info(f"Cloning repository {repo_url} to {self.repo_path}")
|
logger.info(f"Cloning repositories {self.remotes} to {self.repo_path}")
|
||||||
os.makedirs(self.repo_path, exist_ok=True)
|
os.makedirs(self.repo_path, exist_ok=True)
|
||||||
try:
|
try:
|
||||||
if os.path.exists(os.path.join(self.repo_path, ".git")):
|
if os.path.exists(os.path.join(self.repo_path, ".git")):
|
||||||
logger.info(f"Repository already cloned at {self.repo_path}, fetching updates.")
|
logger.info(f"Repository already cloned at {self.repo_path}, fetching updates.")
|
||||||
repo = git.Repo(self.repo_path)
|
repo = git.Repo(self.repo_path)
|
||||||
if 'origin' not in repo.remotes or repo.remotes.origin.url != self._get_auth_git_url(repo_url):
|
|
||||||
repo.create_remote('origin', self._get_auth_git_url(repo_url))
|
|
||||||
result = repo.remotes.origin.fetch(prune=True)
|
|
||||||
if not result or any(fetch_info.flags & fetch_info.ERROR for fetch_info in result):
|
|
||||||
raise BaseException(f"Failed to fetch updates for {repo_url}")
|
|
||||||
else:
|
else:
|
||||||
repo = git.Repo.init(self.repo_path)
|
repo = git.Repo.init(self.repo_path)
|
||||||
repo.remotes.append(repo.create_remote(
|
|
||||||
'origin',
|
fetched_remotes = 0
|
||||||
self._get_auth_git_url(repo_url)
|
for entry in self.remotes:
|
||||||
))
|
remote_name = entry["name"]
|
||||||
if self.branchNamePrefix != "":
|
repository_url = entry["url"]
|
||||||
repo.config_writer().set_value('remote "origin"', "fetch",
|
try:
|
||||||
f"+refs/heads/{self.branchNamePrefix}/*:refs/remotes/origin/{self.branchNamePrefix}/*").release()
|
auth_url = self._get_auth_git_url(repository_url)
|
||||||
repo.remotes.origin.fetch(prune=True)
|
if remote_name in repo.remotes:
|
||||||
if not os.path.exists(os.path.join(self.repo_path, ".git")):
|
remote = repo.remotes[remote_name]
|
||||||
raise BaseException(f"Failed to clone repository {repo_url} to {self.repo_path}")
|
if remote.url != auth_url:
|
||||||
|
remote.set_url(auth_url)
|
||||||
|
else:
|
||||||
|
remote = repo.create_remote(remote_name, auth_url)
|
||||||
|
with repo.config_writer() as config:
|
||||||
|
config.set_value(
|
||||||
|
f'remote "{remote_name}"',
|
||||||
|
'fetch',
|
||||||
|
f'+refs/heads/*:refs/remotes/{remote_name}/*',
|
||||||
|
)
|
||||||
|
if remote_name == "origin" and self.branchNamePrefix != "":
|
||||||
|
with repo.config_writer() as config:
|
||||||
|
config.set_value('remote "origin"', "fetch",
|
||||||
|
f"+refs/heads/{self.branchNamePrefix}/*:refs/remotes/origin/{self.branchNamePrefix}/*")
|
||||||
|
result = remote.fetch(prune=True)
|
||||||
|
if not result or any(fetch_info.flags & fetch_info.ERROR for fetch_info in result):
|
||||||
|
raise BaseException(f"Failed to fetch updates for {remote_name}")
|
||||||
|
fetched_remotes += 1
|
||||||
|
except BaseException as remote_error:
|
||||||
|
if "File contains no section headers" in str(remote_error):
|
||||||
|
raise
|
||||||
|
self.errors.append(f"Unable to fetch remote {remote_name} ({repository_url}): {remote_error}")
|
||||||
|
logger.warning("Unable to fetch remote %s (%s): %s", remote_name, repository_url, remote_error)
|
||||||
|
if fetched_remotes == 0:
|
||||||
|
logger.warning("No configured git remotes are available; keeping the local repository state")
|
||||||
|
if not os.path.exists(os.path.join(self.repo_path, ".git")):
|
||||||
|
raise BaseException(f"Failed to clone repositories {self.remotes} to {self.repo_path}")
|
||||||
except BaseException as e:
|
except BaseException as e:
|
||||||
logger.error(f"Error during git clone/fetch, removing directory {self.repo_path}: {str(e)}")
|
logger.error(f"Error during git clone/fetch, removing directory {self.repo_path}: {str(e)}")
|
||||||
shutil.rmtree(self.repo_path)
|
shutil.rmtree(self.repo_path)
|
||||||
@@ -73,21 +141,24 @@ class GitClone(AbstractStep[str]):
|
|||||||
repo = git.Repo(self.repo_path)
|
repo = git.Repo(self.repo_path)
|
||||||
result: Dict[str, List[Any]] = {}
|
result: Dict[str, List[Any]] = {}
|
||||||
for ref in repo.refs:
|
for ref in repo.refs:
|
||||||
if ref.name.startswith('origin/') and not ref.name.startswith('origin/HEAD'):
|
if not ref.is_remote() or ref.name.endswith('/HEAD'):
|
||||||
branch_name = ref.name[len('origin/'):]
|
continue
|
||||||
if not branch_name.startswith('auto/'): # Skip auto branches
|
remote_name, branch_name = ref.name.split('/', 1)
|
||||||
result[branch_name] = []
|
if branch_name.startswith(AUTO_BRANCH_PREFIX) or branch_name.startswith('auto/'):
|
||||||
cmt = [ref.commit]
|
continue
|
||||||
for _ in range(10):
|
branch_key = branch_name if remote_name == 'origin' else ref.name
|
||||||
for commit in cmt:
|
result[branch_key] = []
|
||||||
result[branch_name].append({
|
cmt = [ref.commit]
|
||||||
'hexsha': commit.hexsha,
|
for _ in range(10):
|
||||||
'author': commit.author.name,
|
for commit in cmt:
|
||||||
'date': commit.committed_datetime.isoformat(),
|
result[branch_key].append({
|
||||||
'message': commit.message.strip()
|
'hexsha': commit.hexsha,
|
||||||
})
|
'author': commit.author.name,
|
||||||
|
'date': commit.committed_datetime.isoformat(),
|
||||||
|
'message': commit.message.strip()
|
||||||
|
})
|
||||||
|
|
||||||
cmt = [p for c in cmt for p in c.parents]
|
cmt = [p for c in cmt for p in c.parents]
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
@@ -112,6 +183,18 @@ def ensure_clean(repo: git.Repo) -> None:
|
|||||||
raise BaseException(f"Changes in repo: U{repo.untracked_files}")
|
raise BaseException(f"Changes in repo: U{repo.untracked_files}")
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_branch_ref(repo: git.Repo, branch_key: str, default_remote: str) -> str:
|
||||||
|
# Branch keys can be "branch", "origin/branch", "gitea_admin/branch", etc.
|
||||||
|
# If the key has a remote prefix that matches a known remote, use it
|
||||||
|
# verbatim; otherwise fall back to the primary configured remote so
|
||||||
|
# configs that don't name a remote `origin` still work.
|
||||||
|
if "/" in branch_key:
|
||||||
|
remote_name, _ = branch_key.split("/", 1)
|
||||||
|
if remote_name in repo.remotes:
|
||||||
|
return branch_key
|
||||||
|
return f"{default_remote}/{branch_key}"
|
||||||
|
|
||||||
|
|
||||||
class CheckoutMerged(AbstractStep[CheckoutAndMergeResult]):
|
class CheckoutMerged(AbstractStep[CheckoutAndMergeResult]):
|
||||||
wd: GitClone
|
wd: GitClone
|
||||||
|
|
||||||
@@ -119,7 +202,7 @@ class CheckoutMerged(AbstractStep[CheckoutAndMergeResult]):
|
|||||||
desired_branches: AbstractStep[SharedState],
|
desired_branches: AbstractStep[SharedState],
|
||||||
git_user_email: str,
|
git_user_email: str,
|
||||||
git_user_name: str,
|
git_user_name: str,
|
||||||
push: bool = True,
|
push: bool | str = True,
|
||||||
**kwargs: Any):
|
**kwargs: Any):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
self.wd = wd
|
self.wd = wd
|
||||||
@@ -146,11 +229,19 @@ class CheckoutMerged(AbstractStep[CheckoutAndMergeResult]):
|
|||||||
def find_desired_commits(self, repo: git.Repo, branches: List[Tuple[str, str]]) -> Dict[Commit, str]:
|
def find_desired_commits(self, repo: git.Repo, branches: List[Tuple[str, str]]) -> Dict[Commit, str]:
|
||||||
# Extract commit ids for the selected branches
|
# Extract commit ids for the selected branches
|
||||||
commit_ids: Dict[Commit, str] = {}
|
commit_ids: Dict[Commit, str] = {}
|
||||||
|
# Default remote: prefer the first remote GitClone was configured with
|
||||||
|
# (so non-"origin" configs like github/gitea_admin work without the
|
||||||
|
# caller having to qualify every branch key).
|
||||||
|
default_remote = "origin"
|
||||||
|
if isinstance(getattr(self.wd, "remotes", None), list) and self.wd.remotes:
|
||||||
|
primary = self.wd.remotes[0]["name"]
|
||||||
|
if primary in repo.remotes:
|
||||||
|
default_remote = primary
|
||||||
for branch_pair in branches:
|
for branch_pair in branches:
|
||||||
try:
|
try:
|
||||||
branch_name, desired_commit = branch_pair
|
branch_name, desired_commit = branch_pair
|
||||||
if desired_commit == 'HEAD':
|
if desired_commit == 'HEAD':
|
||||||
commit = repo.commit(f'origin/{branch_name}')
|
commit = repo.commit(_resolve_branch_ref(repo, branch_name, default_remote))
|
||||||
else:
|
else:
|
||||||
commit = repo.commit(desired_commit)
|
commit = repo.commit(desired_commit)
|
||||||
commit_ids[commit] = branch_name
|
commit_ids[commit] = branch_name
|
||||||
@@ -229,16 +320,18 @@ class CheckoutMerged(AbstractStep[CheckoutAndMergeResult]):
|
|||||||
version = '-'.join([x.hexsha[0:8] for x in sorted_commits])
|
version = '-'.join([x.hexsha[0:8] for x in sorted_commits])
|
||||||
|
|
||||||
for ref in repo.refs:
|
for ref in repo.refs:
|
||||||
if ref.is_remote() and ref.commit == repo.head.commit and ref.name != 'origin/HEAD':
|
if ref.is_remote() and ref.commit == repo.head.commit and not ref.name.endswith('/HEAD'):
|
||||||
logger.info(f"Merge commit {ref.commit} corresponds to branch {ref}")
|
logger.info(f"Merge commit {ref.commit} corresponds to branch {ref}")
|
||||||
remote_branch_name = ref.name[len('origin/'):]
|
remote_name, branch_name = ref.name.split('/', 1)
|
||||||
|
remote_branch_name = branch_name if remote_name == 'origin' else ref.name
|
||||||
break
|
break
|
||||||
if self.push and remote_branch_name is None:
|
if self.push:
|
||||||
auto_branch_hash = hashlib.sha1(''.join([x.hexsha for x in sorted_commits]).encode()).hexdigest()
|
auto_branch_hash = hashlib.sha1(''.join([x.hexsha for x in sorted_commits]).encode()).hexdigest()
|
||||||
auto_branch_name = f"auto-{version}"
|
auto_branch_name = f"{AUTO_BRANCH_PREFIX}{version}"
|
||||||
|
push_remote = self.push if isinstance(self.push, str) else "origin"
|
||||||
|
|
||||||
logger.info(f"Pushing {repo.head.commit.hexsha} -> {auto_branch_name}")
|
logger.info(f"Pushing {repo.head.commit.hexsha} -> {auto_branch_name}")
|
||||||
repo.git.push('-f', 'origin', f"HEAD:refs/heads/{auto_branch_name}")
|
repo.git.push('-f', push_remote, f"HEAD:refs/heads/{auto_branch_name}")
|
||||||
remote_branch_name = auto_branch_name
|
remote_branch_name = auto_branch_name
|
||||||
|
|
||||||
return CheckoutAndMergeResult(
|
return CheckoutAndMergeResult(
|
||||||
@@ -272,9 +365,12 @@ class GitUnmerge(AbstractStep[GitUnmergeResult]):
|
|||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
self.wd = wd
|
self.wd = wd
|
||||||
self.check = check
|
self.check = check
|
||||||
|
self.warnings: List[str] = []
|
||||||
|
|
||||||
def progress(self) -> GitUnmergeResult:
|
def progress(self) -> GitUnmergeResult:
|
||||||
|
self.warnings = []
|
||||||
wd = self.wd.progress()
|
wd = self.wd.progress()
|
||||||
|
repo = git.Repo(wd)
|
||||||
deployState: Mapping[str, HasVersion] = self.check.progress()
|
deployState: Mapping[str, HasVersion] = self.check.progress()
|
||||||
|
|
||||||
versions = set([it.version for it in deployState.values()])
|
versions = set([it.version for it in deployState.values()])
|
||||||
@@ -282,20 +378,20 @@ class GitUnmerge(AbstractStep[GitUnmergeResult]):
|
|||||||
raise BaseException(f"Expected exactly one version, got: {versions}")
|
raise BaseException(f"Expected exactly one version, got: {versions}")
|
||||||
|
|
||||||
version = list(versions)[0]
|
version = list(versions)[0]
|
||||||
|
if not version:
|
||||||
|
return GitUnmergeResult(branches=[], columns={"Deployed": {}})
|
||||||
if version is None:
|
if version is None:
|
||||||
raise BaseException(f"Expected exactly one version, got: {versions}")
|
raise BaseException(f"Expected exactly one version, got: {versions}")
|
||||||
repo = git.Repo(wd)
|
|
||||||
childs: Dict[Commit, List[Commit]] | None = None
|
childs: Dict[Commit, List[Commit]] | None = None
|
||||||
if 'auto-' in version:
|
if version.startswith(AUTO_BRANCH_PREFIX):
|
||||||
version_parts = version[len('auto-'):].split('-')
|
version_parts = version[len(AUTO_BRANCH_PREFIX):].split('-')
|
||||||
|
|
||||||
commits: List[Tuple[str, str]] = []
|
commits: List[Tuple[str, str]] = []
|
||||||
for v in version_parts:
|
for v in version_parts:
|
||||||
commit = repo.commit(v)
|
commit = repo.commit(v)
|
||||||
# branches = [head.name for head in repo.heads if head.commit.hexsha == commit.hexsha]
|
branches = [ref.name for ref in repo.refs
|
||||||
branches = [ref.name for ref in repo.remotes.origin.refs if ref.commit.hexsha == commit.hexsha]
|
if ref.is_remote() and not ref.name.endswith('/HEAD') and ref.commit.hexsha == commit.hexsha]
|
||||||
branches = [b[len('origin/'):] for b in branches if
|
branches = [b[len('origin/'):] if b.startswith('origin/') else b for b in branches]
|
||||||
b.startswith('origin/') and not b.startswith('origin/HEAD')]
|
|
||||||
|
|
||||||
if len(branches) == 0 or branches[0].startswith('auto/'):
|
if len(branches) == 0 or branches[0].startswith('auto/'):
|
||||||
if childs is None:
|
if childs is None:
|
||||||
@@ -304,10 +400,9 @@ class GitUnmerge(AbstractStep[GitUnmergeResult]):
|
|||||||
while len(commitsSet) > 0:
|
while len(commitsSet) > 0:
|
||||||
current = commitsSet.pop()
|
current = commitsSet.pop()
|
||||||
for child in childs.get(current, []):
|
for child in childs.get(current, []):
|
||||||
branches = [ref.name for ref in repo.remotes.origin.refs if
|
branches = [ref.name for ref in repo.refs
|
||||||
ref.commit.hexsha == child.hexsha]
|
if ref.is_remote() and not ref.name.endswith('/HEAD') and ref.commit.hexsha == child.hexsha]
|
||||||
branches = [b[len('origin/'):] for b in branches if
|
branches = [b[len('origin/'):] if b.startswith('origin/') else b for b in branches]
|
||||||
b.startswith('origin/') and not b.startswith('origin/HEAD')]
|
|
||||||
|
|
||||||
if len(branches) > 0:
|
if len(branches) > 0:
|
||||||
commitsSet = set()
|
commitsSet = set()
|
||||||
|
|||||||
+23
-7
@@ -94,6 +94,15 @@ class WebApp:
|
|||||||
merged = _merge_dicts(merged, connector.branches)
|
merged = _merge_dicts(merged, connector.branches)
|
||||||
return merged
|
return merged
|
||||||
|
|
||||||
|
def get_selection_summary(self) -> Dict[str, Dict[str, Any]]:
|
||||||
|
return {
|
||||||
|
env_id: {
|
||||||
|
"branches": env.get("branches", []),
|
||||||
|
"dry": env.get("dry"),
|
||||||
|
}
|
||||||
|
for env_id, env in self.get_global_envs_to_emit().items()
|
||||||
|
}
|
||||||
|
|
||||||
# --- Async scheduling from sync threads ---
|
# --- Async scheduling from sync threads ---
|
||||||
|
|
||||||
def _schedule_async(self, coro: Any) -> None:
|
def _schedule_async(self, coro: Any) -> None:
|
||||||
@@ -107,12 +116,12 @@ class WebApp:
|
|||||||
disconnected = set()
|
disconnected = set()
|
||||||
message = custom_json_dumps({event: data})
|
message = custom_json_dumps({event: data})
|
||||||
|
|
||||||
for websocket in self.ws_connections.keys():
|
for websocket, state in self.ws_connections.items():
|
||||||
if self.ws_connections[websocket].get(event) == message:
|
if state.get(event) == message:
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
await websocket.send_text(message)
|
await websocket.send_text(message)
|
||||||
self.ws_connections[websocket][event] = message
|
state[event] = message
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error sending to websocket: {e}")
|
logger.error(f"Error sending to websocket: {e}")
|
||||||
disconnected.add(websocket)
|
disconnected.add(websocket)
|
||||||
@@ -163,7 +172,8 @@ class WebApp:
|
|||||||
|
|
||||||
async def websocket_endpoint(self, websocket: WebSocket) -> None:
|
async def websocket_endpoint(self, websocket: WebSocket) -> None:
|
||||||
await websocket.accept()
|
await websocket.accept()
|
||||||
self.ws_connections[websocket] = {}
|
state = self.ws_connections.setdefault(websocket, {})
|
||||||
|
logger.info("UI connected: selected=%s", self.get_selection_summary())
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Send initial state on connect and record it so duplicate broadcasts are suppressed
|
# Send initial state on connect and record it so duplicate broadcasts are suppressed
|
||||||
@@ -172,9 +182,9 @@ class WebApp:
|
|||||||
version_payload = custom_json_dumps({"version": self.get_version()})
|
version_payload = custom_json_dumps({"version": self.get_version()})
|
||||||
await websocket.send_text(version_payload)
|
await websocket.send_text(version_payload)
|
||||||
await websocket.send_text(branches_payload)
|
await websocket.send_text(branches_payload)
|
||||||
self.ws_connections[websocket]["branches"] = branches_payload
|
state["branches"] = branches_payload
|
||||||
await websocket.send_text(envs_payload)
|
await websocket.send_text(envs_payload)
|
||||||
self.ws_connections[websocket]["environments"] = envs_payload
|
state["environments"] = envs_payload
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
data = await websocket.receive_text()
|
data = await websocket.receive_text()
|
||||||
@@ -182,7 +192,12 @@ class WebApp:
|
|||||||
|
|
||||||
if "update" in message:
|
if "update" in message:
|
||||||
update_data = message.get("update") or {}
|
update_data = message.get("update") or {}
|
||||||
logger.info(f"Received environment update: {update_data}")
|
logger.info(
|
||||||
|
"UI selection update: env=%s branches=%s dry=%s",
|
||||||
|
update_data.get('id', ''),
|
||||||
|
update_data.get('branches'),
|
||||||
|
update_data.get('dry'),
|
||||||
|
)
|
||||||
if self.secondaryManager:
|
if self.secondaryManager:
|
||||||
await self.secondaryManager.send({"update": update_data})
|
await self.secondaryManager.send({"update": update_data})
|
||||||
id = update_data.get('id', '')
|
id = update_data.get('id', '')
|
||||||
@@ -222,6 +237,7 @@ class WebApp:
|
|||||||
if isinstance(p, CachingStep):
|
if isinstance(p, CachingStep):
|
||||||
p.reset()
|
p.reset()
|
||||||
logger.info(f"Updated environment {env.id} branches to {update_data.get('branches')}, dry={update_data.get('dry')}")
|
logger.info(f"Updated environment {env.id} branches to {update_data.get('branches')}, dry={update_data.get('dry')}")
|
||||||
|
logger.info("UI selection resolved: selected=%s", self.get_selection_summary())
|
||||||
self.core.environment_update_event.set()
|
self.core.environment_update_event.set()
|
||||||
|
|
||||||
await self.broadcast_environments(self.get_global_envs_to_emit())
|
await self.broadcast_environments(self.get_global_envs_to_emit())
|
||||||
|
|||||||
+1
-1
@@ -17,7 +17,7 @@ services:
|
|||||||
- VIRTUAL_HOST=brencher.rudolf.keenetic.link
|
- VIRTUAL_HOST=brencher.rudolf.keenetic.link
|
||||||
- LETSENCRYPT_HOST=brencher.rudolf.keenetic.link
|
- LETSENCRYPT_HOST=brencher.rudolf.keenetic.link
|
||||||
- VERSION=${version}
|
- VERSION=${version}
|
||||||
- PROFILES=brencher2,torrserv_proxy,immich,gmail_mcp,hermes,hermes_infra,gitea
|
- PROFILES=brencher2,torrserv_proxy,immich,gmail_mcp,hermes,hermes_infra,gitea,connectivity_tester
|
||||||
- SECONDARY_BRENCHER=http://host.docker.internal:5002
|
- SECONDARY_BRENCHER=http://host.docker.internal:5002
|
||||||
deploy:
|
deploy:
|
||||||
replicas: 1
|
replicas: 1
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
# Brencher — backend use cases
|
||||||
|
|
||||||
|
## Цель приложения
|
||||||
|
|
||||||
|
Brencher получает состояние Git-репозиториев и Docker Swarm, сопоставляет выбранные коммиты с развёрнутым состоянием и запускает pipeline сборки/развёртывания. Этот файл описывает сценарии клиента backend API: запрос, ответ, ошибку и серверный побочный эффект.
|
||||||
|
|
||||||
|
## Граница API
|
||||||
|
|
||||||
|
- REST endpoint-ы текущего backend: `GET /state`, `GET /branches` и `GET /`/static resources.
|
||||||
|
- Изменение выбранных веток, применение, dry run и передача UI-событий выполняются через `WebSocket /ws`, а не через REST mutation endpoint.
|
||||||
|
- Данные API являются состоянием процесса и не образуют постоянное хранилище.
|
||||||
|
|
||||||
|
## REST use cases
|
||||||
|
|
||||||
|
### B-01. Получить состояние окружений — `GET /state`
|
||||||
|
|
||||||
|
1. Клиент отправляет `GET /state`.
|
||||||
|
2. Backend возвращает JSON с текущей версией, окружениями, выбранными ветками/коммитами, deployed-состоянием и текущими Jobs/pipeline, если они доступны.
|
||||||
|
3. Если состояние ещё не собрано, ответ содержит начальное/пустое состояние, а pipeline продолжает работу асинхронно.
|
||||||
|
4. Ошибка backend или недоступное окружение отражается в состоянии соответствующего окружения и логах; REST сам по себе не запускает deploy.
|
||||||
|
|
||||||
|
### B-02. Получить доступные ветки — `GET /branches`
|
||||||
|
|
||||||
|
1. Клиент отправляет `GET /branches`.
|
||||||
|
2. Backend возвращает ветки, полученные из настроенных remotes, с remote-префиксами при необходимости.
|
||||||
|
3. Ответ может измениться после fetch или pipeline update.
|
||||||
|
4. Ошибка Git/fetch не превращается в успешный полный список и фиксируется как ошибка обработки.
|
||||||
|
|
||||||
|
### B-03. Получить веб-приложение — `GET /`
|
||||||
|
|
||||||
|
1. Клиент отправляет `GET /`.
|
||||||
|
2. Backend возвращает `frontend/index.html`; статические CSS/JS-файлы обслуживаются через static route.
|
||||||
|
3. HTTP-ответ загружает UI, но не устанавливает realtime-соединение: UI отдельно открывает `/ws`.
|
||||||
|
|
||||||
|
### B-04. Получить статический ресурс или неизвестный путь
|
||||||
|
|
||||||
|
1. Клиент запрашивает путь через HTTP.
|
||||||
|
2. Backend пытается обслужить файл frontend.
|
||||||
|
3. Отсутствующий ресурс возвращается как HTTP-ошибка/не найденный ресурс согласно FastAPI/static handler.
|
||||||
|
|
||||||
|
## WebSocket-команды, доступные backend-клиенту
|
||||||
|
|
||||||
|
Эти сценарии не являются REST, но необходимы для полного описания backend API: текущий код принимает команды по `/ws`.
|
||||||
|
|
||||||
|
### B-05. Открыть `/ws` и получить начальное состояние
|
||||||
|
|
||||||
|
1. Клиент устанавливает WebSocket-соединение.
|
||||||
|
2. Backend отправляет сообщения с `version`, `branches` и `environments`.
|
||||||
|
3. Backend регистрирует соединение и его последнее отправленное состояние.
|
||||||
|
4. При disconnect соединение удаляется из реестра.
|
||||||
|
|
||||||
|
### B-06. Передать обновление выбранного окружения
|
||||||
|
|
||||||
|
1. Клиент отправляет JSON-сообщение с изменением `environment`, `branches`/commit selection и параметрами применения.
|
||||||
|
2. Backend обновляет состояние окружения и запускает соответствующую обработку.
|
||||||
|
3. Backend рассылает новое состояние подключённым WebSocket-клиентам.
|
||||||
|
4. Некорректный JSON, неизвестное окружение или ошибка обработки становятся ошибкой WebSocket/pipeline.
|
||||||
|
|
||||||
|
### B-07. Запустить применение или dry run
|
||||||
|
|
||||||
|
1. Клиент отправляет команду применения с выбранной веткой, `HEAD`, историческим или произвольным commit.
|
||||||
|
2. Для нескольких веток backend может выполнить merge; конфликт останавливает соответствующий шаг.
|
||||||
|
3. При dry run backend выполняет анализ и подготовительные шаги, но не должен выполнять финальное развёртывание.
|
||||||
|
4. Результат, Jobs и ошибка публикуются через WebSocket; отдельного REST endpoint для mutation нет.
|
||||||
|
|
||||||
|
## Серверные pipeline use cases
|
||||||
|
|
||||||
|
### B-08. Обновить Git-состояние
|
||||||
|
|
||||||
|
1. Backend выполняет fetch настроенных Git remotes.
|
||||||
|
2. Клиент получает новые branches/commits через `/branches` или WebSocket update.
|
||||||
|
3. Ошибка credentials, сети или отсутствующего remote прерывает зависимые шаги.
|
||||||
|
4. Для основного профиля `brencher` используются GitHub и `hermes/brencher`; `admin/brencher` не используется. `brencher2` — независимый профиль.
|
||||||
|
|
||||||
|
### B-09. Разрешить выбранный commit
|
||||||
|
|
||||||
|
1. Backend принимает branch, `HEAD`, исторический или произвольный commit.
|
||||||
|
2. Проверяет наличие ref/commit и получает соответствующее состояние.
|
||||||
|
3. Неизвестный ref/commit становится ошибкой pipeline.
|
||||||
|
4. Имена одинаковых веток разных remotes должны сохранять remote-контекст.
|
||||||
|
|
||||||
|
### B-10. Объединить несколько веток
|
||||||
|
|
||||||
|
1. Backend получает несколько выбранных источников.
|
||||||
|
2. Выполняет checkout и merge в рабочем каталоге.
|
||||||
|
3. При конфликте merge pipeline останавливается и публикует ошибку.
|
||||||
|
4. Устаревшее состояние токена/выбора может быть отклонено сервером; отдельное structured conflict-сообщение текущий код не гарантирует.
|
||||||
|
|
||||||
|
### B-11. Проверить deployed-состояние Swarm
|
||||||
|
|
||||||
|
1. Backend обращается к Docker API/socket и читает labels, image/version, stack/service и replica state.
|
||||||
|
2. Docker Swarm является целью проверки и deploy, а не обязательным исполнителем image build.
|
||||||
|
3. Недоступный socket, stack или service публикуется как ошибка.
|
||||||
|
|
||||||
|
### B-12. Запустить сборку и публикацию образа
|
||||||
|
|
||||||
|
1. В конфигурациях, где включён локальный build, backend подготавливает compose/build pipeline.
|
||||||
|
2. В конфигурациях Actions backend может вызвать Gitea Actions workflow и дождаться его результата; сборка и push выполняются runner-ом.
|
||||||
|
3. Публикация в registry является условной; в текущем основном `brencher` она отключена (`publish=False`).
|
||||||
|
4. Ошибка build, workflow, registry или credentials не считается успешным pipeline.
|
||||||
|
|
||||||
|
### B-13. Выполнить deploy
|
||||||
|
|
||||||
|
1. После успешного pipeline backend выполняет Docker Swarm deploy либо делегирует его настроенному шагу.
|
||||||
|
2. После deploy проверяет version/labels и replicas.
|
||||||
|
3. Несовпадение версии или количества replicas публикуется как ошибка/неуспешное состояние.
|
||||||
|
4. Отдельной rollback-кнопки или гарантированного rollback API нет.
|
||||||
|
|
||||||
|
### B-14. Автоматически обнаружить drift
|
||||||
|
|
||||||
|
1. `GitUnmerge` сопоставляет deployed label с remote HEAD и desired branches.
|
||||||
|
2. При отличии backend формирует pipeline автоматически, без UI-команды.
|
||||||
|
3. При отсутствии diff deploy не выполняется.
|
||||||
|
4. Конфигурация без корректно подключённого `GitUnmerge` не может самостоятельно восстановить desired branches после перезапуска.
|
||||||
|
|
||||||
|
### B-15. Проверить URL health check
|
||||||
|
|
||||||
|
1. Настроенный профиль выполняет HTTP GET к сервису.
|
||||||
|
2. Проверяет HTTP 200, JSON и ожидаемые поля рекурсивно.
|
||||||
|
3. Несовпадение ответа или недоступность сервиса становится ошибкой health-check шага.
|
||||||
|
|
||||||
|
### B-16. Синхронизировать secondary Brencher
|
||||||
|
|
||||||
|
1. При заданном `SECONDARY_BRENCHER` backend подключается к отдельному удалённому экземпляру по WebSocket.
|
||||||
|
2. Передаёт update и объединяет полученные branches/environments с локальными.
|
||||||
|
3. Конфликт одинаковых environment ID не маскируется.
|
||||||
|
4. При обрыве выполняются reconnect/retry с задержкой; после исчерпания попыток ошибка пишется в журнал.
|
||||||
|
|
||||||
|
## Операционные и security boundaries
|
||||||
|
|
||||||
|
### B-17. Запустить разные режимы
|
||||||
|
|
||||||
|
1. Оператор задаёт `PROFILES` или CLI-аргумент и может исключить профиль префиксом `-`.
|
||||||
|
2. `noweb` запускает backend без web UI; глобальный `dry` включает dry run.
|
||||||
|
3. Порт, конфигурация, secondary URL и credentials задаются внешней конфигурацией.
|
||||||
|
|
||||||
|
### B-18. Обработать несколько клиентов
|
||||||
|
|
||||||
|
1. Backend хранит несколько WebSocket-соединений.
|
||||||
|
2. Обновление рассылается подключённым клиентам, если payload изменился; одинаковые payload дедуплицируются для конкретного соединения.
|
||||||
|
3. Один клиент может увидеть устаревший выбор другого; сервер отклоняет часть stale-состояний, но не предоставляет полноценную блокировку операторов.
|
||||||
|
|
||||||
|
### B-19. Зафиксировать границу доступа
|
||||||
|
|
||||||
|
1. Backend предоставляет статус и команды управления через web/API layer.
|
||||||
|
2. В исходном web layer нет встроенной authentication/authorization-проверки.
|
||||||
|
3. Защита должна обеспечиваться reverse proxy, сетью или внешним механизмом доступа.
|
||||||
|
4. Нельзя считать открытый endpoint безопасным только потому, что он использует FastAPI/WebSocket.
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
# Сценарии, не покрытые тестами
|
||||||
|
|
||||||
|
## Цель документа
|
||||||
|
|
||||||
|
Этот документ фиксирует сценарии из требований Brencher, для которых в текущем репозитории нет автоматического теста или есть только частичное покрытие. Проверка выполнена по файлам `tests/test_*.py`, тестовой документации и исходникам backend/frontend.
|
||||||
|
|
||||||
|
Ссылки `[B-*]` и `[U-*]` ведут на требования в документах:
|
||||||
|
|
||||||
|
- [Backend use cases](USE_CASES_BACKEND.md)
|
||||||
|
- [UI use cases](USE_CASES_UI.md)
|
||||||
|
- [AGENTS.md](../AGENTS.md) — требования к self-driving/autodeploy-конфигурации
|
||||||
|
- [tests/README.md](../tests/README.md) — заявленная область существующих integration tests
|
||||||
|
|
||||||
|
## Границы текущего покрытия
|
||||||
|
|
||||||
|
Покрыты или частично покрыты существующими тестами:
|
||||||
|
|
||||||
|
- Git clone, named remotes, validation и восстановление повреждённого local config — `tests/test_git_integration.py`;
|
||||||
|
- checkout/merge одной, двух и трёх веток, fast-forward, merge conflict и auto branch — `tests/test_git_integration.py`;
|
||||||
|
- GitUnmerge для valid/invalid version и non-HEAD commit — `tests/test_git_integration.py`;
|
||||||
|
- stale token на уровне shared state — `tests/test_cached_env.py`, `tests/test_processing_initial_branches.py`;
|
||||||
|
- apply через UI и повторное появление apply при конфликте — `tests/test_apply_changes.py`;
|
||||||
|
- dry run и переход к deploy после его выключения — `tests/test_dry_run_playwright.py`;
|
||||||
|
- отображение deployed column после apply/deploy — `tests/test_deploy_column_playwright.py`;
|
||||||
|
- кэширование pipeline step — `tests/test_caching_step.py`.
|
||||||
|
|
||||||
|
Эти тесты не покрывают весь пользовательский сценарий целиком: например, проверка `GET /state` на HTTP 200 не проверяет все поля ответа, а локальный container test не является тестом Docker Swarm rollout.
|
||||||
|
|
||||||
|
## Непокрытые UI-сценарии
|
||||||
|
|
||||||
|
### NU-09. Красная рамка toggle-кнопки при проблемном pipeline
|
||||||
|
|
||||||
|
**Требование:** [U-06](USE_CASES_UI.md#u-06-отфильтровать-окружения-toggle-кнопками).
|
||||||
|
|
||||||
|
Нет автоматического UI-теста, который проверяет:
|
||||||
|
|
||||||
|
- красную рамку для окружения с `error`-шагом;
|
||||||
|
- красную рамку для окружения с `is_running`-шагом;
|
||||||
|
- отсутствие красной рамки у окружения, где все шаги завершены успешно;
|
||||||
|
- обновление рамки после WebSocket-сообщения с новым pipeline state;
|
||||||
|
- сохранение возможности включать и выключать проблемную toggle-кнопку.
|
||||||
|
|
||||||
|
## Непокрытые backend-сценарии
|
||||||
|
|
||||||
|
### NB-01. Получение главной страницы и static resource
|
||||||
|
|
||||||
|
**Требование:** [B-03](USE_CASES_BACKEND.md#b-03-получить-веб-приложение--get) и [B-04](USE_CASES_BACKEND.md#b-04-получить-статический-ресурс-или-неизвестный-путь).
|
||||||
|
|
||||||
|
Нет теста, который проверяет:
|
||||||
|
|
||||||
|
- `GET /` и наличие `index.html`;
|
||||||
|
- загрузку `app.js` и `styles.css`;
|
||||||
|
- ошибку неизвестного static path;
|
||||||
|
- поведение при недоступном/повреждённом статическом ресурсе.
|
||||||
|
|
||||||
|
Связанные исходники: [`backend/web.py`](../backend/web.py), [`frontend/index.html`](../frontend/index.html).
|
||||||
|
|
||||||
|
### NB-02. Полный контракт REST `GET /state`
|
||||||
|
|
||||||
|
**Требование:** [B-01](USE_CASES_BACKEND.md#b-01-получить-состояние-окружений--get-state).
|
||||||
|
|
||||||
|
Существующие тесты проверяют в основном HTTP 200 и отдельные поля. Нет contract-теста на:
|
||||||
|
|
||||||
|
- `version`;
|
||||||
|
- `branches_token`;
|
||||||
|
- `dry`;
|
||||||
|
- desired branches/commits;
|
||||||
|
- deployed columns;
|
||||||
|
- Jobs и pipeline statuses;
|
||||||
|
- пустое/начальное состояние;
|
||||||
|
- ошибку отдельного окружения без падения всего ответа.
|
||||||
|
|
||||||
|
Связанные тесты: [`test_deploy_column_playwright.py`](../tests/test_deploy_column_playwright.py), [`test_apply_changes.py`](../tests/test_apply_changes.py).
|
||||||
|
|
||||||
|
### NB-03. Полный контракт REST `GET /branches`
|
||||||
|
|
||||||
|
**Требование:** [B-02](USE_CASES_BACKEND.md#b-02-получить-доступные-ветки--get-branches).
|
||||||
|
|
||||||
|
Нет отдельного REST contract-теста на:
|
||||||
|
|
||||||
|
- структуру `{environment: {branch: commits}}`;
|
||||||
|
- commit objects и их поля;
|
||||||
|
- несколько remotes и remote-префиксы в HTTP-ответе;
|
||||||
|
- изменение результата после fetch;
|
||||||
|
- ошибку Git/fetch.
|
||||||
|
|
||||||
|
Связанный код: [`backend/web.py`](../backend/web.py), [`backend/steps/git.py`](../backend/steps/git.py).
|
||||||
|
|
||||||
|
### NB-04. WebSocket initial state, malformed messages и unknown environment
|
||||||
|
|
||||||
|
**Требования:** [B-05](USE_CASES_BACKEND.md#b-05-открыть-ws-и-получить-начальное-состояние) и [B-06](USE_CASES_BACKEND.md#b-06-передать-обновление-выбранного-окружения).
|
||||||
|
|
||||||
|
Playwright-тесты используют WebSocket косвенно, но нет backend-теста на:
|
||||||
|
|
||||||
|
- точный порядок/состав initial `version` → `branches` → `environments`;
|
||||||
|
- несколько клиентов и независимое состояние deduplication;
|
||||||
|
- malformed JSON;
|
||||||
|
- неизвестное имя окружения;
|
||||||
|
- disconnect cleanup;
|
||||||
|
- ошибку отправки broadcast одному клиенту.
|
||||||
|
|
||||||
|
Связанный код: [`backend/web.py`](../backend/web.py).
|
||||||
|
|
||||||
|
### NB-05. Git credentials и ошибки внешнего Git
|
||||||
|
|
||||||
|
**Требование:** [B-08](USE_CASES_BACKEND.md#b-08-обновить-git-состояние).
|
||||||
|
|
||||||
|
Git integration tests работают с локальными repositories и не проверяют:
|
||||||
|
|
||||||
|
- authentication failure GitHub/Gitea;
|
||||||
|
- отсутствие или неправильные `GIT_USERNAME`/`GIT_PASSWORD`;
|
||||||
|
- network timeout и недоступный remote;
|
||||||
|
- поведение pipeline после failed fetch;
|
||||||
|
- сохранение корректного состояния после частично успешного fetch нескольких remotes.
|
||||||
|
|
||||||
|
Связанные исходники: [`backend/steps/git.py`](../backend/steps/git.py), [`README.instruction.md`](../README.instruction.md).
|
||||||
|
|
||||||
|
### NB-06. Выбор исторического и произвольного commit через backend
|
||||||
|
|
||||||
|
**Требование:** [B-07](USE_CASES_BACKEND.md#b-07-запустить-применение-или-dry-run) и [B-09](USE_CASES_BACKEND.md#b-09-разрешить-выбранный-commit).
|
||||||
|
|
||||||
|
Тесты проверяют branch/`HEAD` и внутренний Git commit resolution, но нет API/UI integration-теста на:
|
||||||
|
|
||||||
|
- исторический commit из branch history;
|
||||||
|
- произвольный полный или короткий SHA;
|
||||||
|
- неизвестный ref;
|
||||||
|
- commit, недоступный в выбранном remote;
|
||||||
|
- различение одинакового имени branch в разных remotes.
|
||||||
|
|
||||||
|
Связанные тесты: [`test_git_integration.py`](../tests/test_git_integration.py), [`docs/USE_CASES_UI.md`](USE_CASES_UI.md).
|
||||||
|
|
||||||
|
### NB-07. Swarm state inspection
|
||||||
|
|
||||||
|
**Требование:** [B-11](USE_CASES_BACKEND.md#b-11-проверить-deployed-состояние-swarm).
|
||||||
|
|
||||||
|
Текущие Playwright-тесты используют обычный Docker container. Нет теста на Docker Swarm API/socket, который проверяет:
|
||||||
|
|
||||||
|
- чтение `org.brencher.version` label;
|
||||||
|
- stack/service image;
|
||||||
|
- desired и running replicas;
|
||||||
|
- unavailable stack/service;
|
||||||
|
- недоступный Docker socket;
|
||||||
|
- несовпадение deployed version.
|
||||||
|
|
||||||
|
Связанный код: [`backend/steps/docker.py`](../backend/steps/docker.py), [`backend/steps/shared_state.py`](../backend/steps/shared_state.py).
|
||||||
|
|
||||||
|
### NB-08. Actions workflow, registry и deploy после workflow
|
||||||
|
|
||||||
|
**Требования:** [B-12](USE_CASES_BACKEND.md#b-12-запустить-сборку-и-публикацию-образа) и [B-13](USE_CASES_BACKEND.md#b-13-выполнить-deploy).
|
||||||
|
|
||||||
|
Нет теста на configuration-dependent Actions flow:
|
||||||
|
|
||||||
|
- dispatch Gitea Actions workflow;
|
||||||
|
- ожидание завершения workflow;
|
||||||
|
- failed/cancelled workflow;
|
||||||
|
- credentials registry;
|
||||||
|
- pull уже опубликованного image на Swarm node;
|
||||||
|
- `docker stack deploy` и проверку replicas/version после deploy;
|
||||||
|
- отсутствие локального build/push при `buildDocker=None`.
|
||||||
|
|
||||||
|
Требование self-driving pipeline и порядок шагов описаны в [`AGENTS.md`](../AGENTS.md#build-delegation-pattern-actions). Связанные исходники: [`backend/steps/actions.py`](../backend/steps/actions.py), [`backend/steps/docker.py`](../backend/steps/docker.py).
|
||||||
|
|
||||||
|
### NB-09. Автоматический drift/autodeploy без UI-команды
|
||||||
|
|
||||||
|
**Требование:** [B-14](USE_CASES_BACKEND.md#b-14-автоматически-обнаружить-drift).
|
||||||
|
|
||||||
|
GitUnmerge тестируется изолированно, но нет end-to-end теста, который:
|
||||||
|
|
||||||
|
1. запускает backend с deployed Swarm label;
|
||||||
|
2. меняет remote HEAD;
|
||||||
|
3. ждёт polling cycle;
|
||||||
|
4. проверяет автоматический pipeline без `environment_update` из UI;
|
||||||
|
5. проверяет новый image/version и replicas.
|
||||||
|
|
||||||
|
Это прямо требуется checklist-ом [`AGENTS.md`](../AGENTS.md#verification-checklist): push branch, дождаться polling cycle и подтвердить redeploy без UI update.
|
||||||
|
|
||||||
|
### NB-10. Health check
|
||||||
|
|
||||||
|
**Требование:** [B-15](USE_CASES_BACKEND.md#b-15-проверить-url-health-check).
|
||||||
|
|
||||||
|
Нет теста на `UrlCheck`/HTTP health-check flow:
|
||||||
|
|
||||||
|
- HTTP 200 с ожидаемым JSON;
|
||||||
|
- неправильный status code;
|
||||||
|
- невалидный JSON;
|
||||||
|
- рекурсивное несовпадение expected fields;
|
||||||
|
- timeout и недоступный service;
|
||||||
|
- влияние failed health check на pipeline/deploy status.
|
||||||
|
|
||||||
|
Связанный код: backend-конфигурации с `UrlCheck` и соответствующий pipeline step.
|
||||||
|
|
||||||
|
### NB-11. Secondary Brencher
|
||||||
|
|
||||||
|
**Требование:** [B-16](USE_CASES_BACKEND.md#b-16-синхронизировать-secondary-brencher).
|
||||||
|
|
||||||
|
Нет теста на `SECONDARY_BRENCHER`:
|
||||||
|
|
||||||
|
- подключение к remote `/ws`;
|
||||||
|
- forwarding update;
|
||||||
|
- объединение branches/environments;
|
||||||
|
- duplicate environment ID;
|
||||||
|
- reconnect и backoff;
|
||||||
|
- исчерпание retry attempts.
|
||||||
|
|
||||||
|
Связанный код: [`backend/secondary.py`](../backend/secondary.py).
|
||||||
|
|
||||||
|
### NB-12. Startup modes, profiles и restart recovery
|
||||||
|
|
||||||
|
**Требование:** [B-17](USE_CASES_BACKEND.md#b-17-запустить-разные-режимы).
|
||||||
|
|
||||||
|
Нет теста на:
|
||||||
|
|
||||||
|
- `PROFILES` с несколькими профилями;
|
||||||
|
- исключение профиля через `-profile`;
|
||||||
|
- `noweb` headless mode;
|
||||||
|
- глобальный `dry` startup mode;
|
||||||
|
- custom port/configuration;
|
||||||
|
- восстановление state после backend restart;
|
||||||
|
- отличие локального `brencher2` profile от `SECONDARY_BRENCHER`.
|
||||||
|
|
||||||
|
Связанный код: [`backend/app.py`](../backend/app.py), [`backend/discover_envs.py`](../backend/discover_envs.py).
|
||||||
|
|
||||||
|
### NB-13. Multi-client concurrency
|
||||||
|
|
||||||
|
**Требование:** [B-18](USE_CASES_BACKEND.md#b-18-обработать-несколько-клиентов).
|
||||||
|
|
||||||
|
Нет теста на два или более одновременно подключённых клиента:
|
||||||
|
|
||||||
|
- broadcast одного update всем клиентам;
|
||||||
|
- dedup одинакового payload для каждого клиента;
|
||||||
|
- disconnect одного клиента без влияния на остальные;
|
||||||
|
- параллельные updates разных окружений;
|
||||||
|
- race при одновременном изменении одного окружения.
|
||||||
|
|
||||||
|
Связанный код: [`backend/web.py`](../backend/web.py).
|
||||||
|
|
||||||
|
### NB-14. Security boundary
|
||||||
|
|
||||||
|
**Требование:** [B-19](USE_CASES_BACKEND.md#b-19-зафиксировать-границу-доступа).
|
||||||
|
|
||||||
|
Нет security integration-теста, который проверяет явно заявленную границу:
|
||||||
|
|
||||||
|
- REST endpoints доступны без встроенной auth/authz;
|
||||||
|
- WebSocket также не требует application-level credentials;
|
||||||
|
- внешний reverse proxy может ограничить доступ;
|
||||||
|
- неизвестный/неавторизованный клиент не получает ложный `401` от самого backend.
|
||||||
|
|
||||||
|
Связанный код: [`backend/web.py`](../backend/web.py), [`README.instruction.md`](../README.instruction.md).
|
||||||
|
|
||||||
|
## Непокрытые UI-сценарии
|
||||||
|
|
||||||
|
### NU-01. WebSocket reconnect и отсутствие socket leak
|
||||||
|
|
||||||
|
**Требование:** [U-03](USE_CASES_UI.md#u-03-переподключиться-после-разрыва-websocket).
|
||||||
|
|
||||||
|
Нет Playwright-теста, который принудительно закрывает socket и проверяет:
|
||||||
|
|
||||||
|
- reconnect;
|
||||||
|
- повторную загрузку initial state;
|
||||||
|
- отсутствие нескольких параллельных WebSocket instances;
|
||||||
|
- корректное закрытие старого socket;
|
||||||
|
- отображение reconnect/disconnected state.
|
||||||
|
|
||||||
|
Связанные исходники: [`frontend/app.js`](../frontend/app.js), [`backend/web.py`](../backend/web.py).
|
||||||
|
|
||||||
|
### NU-02. Фильтрация окружений toggle-кнопками и текстом
|
||||||
|
|
||||||
|
**Требования:** [U-06](USE_CASES_UI.md#u-06-отфильтровать-окружения-toggle-кнопками) и [U-06a](USE_CASES_UI.md#u-06a-отфильтровать-окружения-текстом).
|
||||||
|
|
||||||
|
Нет UI-теста на:
|
||||||
|
|
||||||
|
- отображение toggle-кнопки для каждого окружения;
|
||||||
|
- выбор одного и нескольких окружений;
|
||||||
|
- фильтрацию branches и Jobs/pipeline по выбранным окружениям;
|
||||||
|
- отображение ссылок, статусов и колонок только выбранных окружений;
|
||||||
|
- поведение при выключении всех кнопок;
|
||||||
|
- сохранение выбора при обновлении WebSocket-состояния;
|
||||||
|
- ввод текстового фильтра, отсутствие совпадений и очистку фильтра;
|
||||||
|
- то, что фильтры не изменяют backend state.
|
||||||
|
|
||||||
|
Связанный исходник: [`frontend/app.js`](../frontend/app.js).
|
||||||
|
|
||||||
|
### NU-03. История и произвольный commit в UI
|
||||||
|
|
||||||
|
**Требования:** [U-10](USE_CASES_UI.md#u-10-выбрать-исторический-commit) и [U-11](USE_CASES_UI.md#u-11-ввести-произвольный-commit).
|
||||||
|
|
||||||
|
Существующие Playwright-тесты выбирают branch/commit из ограниченного сценария, но нет теста на:
|
||||||
|
|
||||||
|
- открытие полной commit history;
|
||||||
|
- исторический commit;
|
||||||
|
- ручной SHA/ref;
|
||||||
|
- невалидный commit;
|
||||||
|
- возврат selection к `HEAD`.
|
||||||
|
|
||||||
|
Связанные файлы: [`frontend/app.js`](../frontend/app.js), [`frontend/index.html`](../frontend/index.html).
|
||||||
|
|
||||||
|
### NU-04. Merge нескольких branches через UI
|
||||||
|
|
||||||
|
**Требование:** [U-13](USE_CASES_UI.md#u-13-объединить-несколько-branches).
|
||||||
|
|
||||||
|
Внутренние Git integration tests проверяют merge, но нет Playwright-теста на выбор нескольких branches, отображение selection и показ merge conflict в Jobs/error panel.
|
||||||
|
|
||||||
|
Связанные тесты/исходники: [`test_git_integration.py`](../tests/test_git_integration.py), [`frontend/app.js`](../frontend/app.js).
|
||||||
|
|
||||||
|
### NU-05. Jobs, pipeline progress и error rendering
|
||||||
|
|
||||||
|
**Требование:** [U-15](USE_CASES_UI.md#u-15-наблюдать-jobs-и-pipeline) и [U-18](USE_CASES_UI.md#u-18-увидеть-ошибку-gitcredentialsregistrydockerhealth-check).
|
||||||
|
|
||||||
|
Тесты проверяют отдельные конечные состояния, но нет полного UI-теста на:
|
||||||
|
|
||||||
|
- все pipeline steps в правильном порядке;
|
||||||
|
- running → success;
|
||||||
|
- running → failed;
|
||||||
|
- текст ошибки и failed step;
|
||||||
|
- повторный запуск после внешней ошибки;
|
||||||
|
- registry/Docker/health-check error display.
|
||||||
|
|
||||||
|
Связанный исходник: [`frontend/app.js`](../frontend/app.js).
|
||||||
|
|
||||||
|
### NU-06. User links
|
||||||
|
|
||||||
|
**Требование:** [U-16](USE_CASES_UI.md#u-16-просмотреть-ссылки-сервиса).
|
||||||
|
|
||||||
|
Нет теста на получение `userLinks`, наличие ссылок в UI, корректный href и отсутствие выдуманной ссылки при пустом `userLinks`.
|
||||||
|
|
||||||
|
Связанные исходники: [`frontend/app.js`](../frontend/app.js), [`frontend/index.html`](../frontend/index.html).
|
||||||
|
|
||||||
|
### NU-07. Automatic update reflected in UI
|
||||||
|
|
||||||
|
**Требование:** [U-17](USE_CASES_UI.md#u-17-увидеть-автоматический-deploy-без-действия-в-ui).
|
||||||
|
|
||||||
|
Нет end-to-end теста, который меняет remote HEAD без UI Update и проверяет отображение нового desired/deployed state и pipeline progress.
|
||||||
|
|
||||||
|
Связанный requirement checklist: [`AGENTS.md`](../AGENTS.md#verification-checklist).
|
||||||
|
|
||||||
|
### NU-08. Secondary state in UI
|
||||||
|
|
||||||
|
**Требование:** [U-20](USE_CASES_UI.md#u-20-работать-с-secondary-brencher).
|
||||||
|
|
||||||
|
Нет UI-теста на объединённое состояние local/secondary, duplicate environment conflict, secondary disconnect и отображение reconnect result.
|
||||||
|
|
||||||
|
Связанные файлы: [`backend/secondary.py`](../backend/secondary.py), [`frontend/app.js`](../frontend/app.js).
|
||||||
|
|
||||||
|
### NU-09. Direct REST diagnostics in UI/browser
|
||||||
|
|
||||||
|
**Требование:** [U-21](USE_CASES_UI.md#u-21-просмотреть-состояние-через-прямой-rest-url).
|
||||||
|
|
||||||
|
Тесты используют `/state` и `/branches` как вспомогательные API, но нет самостоятельного диагностики-теста, который проверяет:
|
||||||
|
|
||||||
|
- открытие endpoint в браузере;
|
||||||
|
- JSON content type;
|
||||||
|
- стабильную структуру ответа;
|
||||||
|
- read-only характер endpoint;
|
||||||
|
- ошибку недоступного окружения в JSON.
|
||||||
|
|
||||||
|
Связанные тесты: [`test_deploy_column_playwright.py`](../tests/test_deploy_column_playwright.py), [`test_containertest.py`](../tests/test_containertest.py).
|
||||||
|
|
||||||
|
## Итог
|
||||||
|
|
||||||
|
Наиболее критичные пробелы для приоритетного добавления тестов:
|
||||||
|
|
||||||
|
1. autodeploy/drift без UI-команды — [B-14](USE_CASES_BACKEND.md#b-14-автоматически-обнаружить-drift), [U-17](USE_CASES_UI.md#u-17-увидеть-автоматический-deploy-без-действия-в-ui);
|
||||||
|
2. Docker Swarm inspect/deploy и Actions workflow — [B-11](USE_CASES_BACKEND.md#b-11-проверить-deployed-состояние-swarm), [B-12](USE_CASES_BACKEND.md#b-12-запустить-сборку-и-публикацию-образа), [B-13](USE_CASES_BACKEND.md#b-13-выполнить-deploy);
|
||||||
|
3. WebSocket initial state/reconnect, multi-client и socket leak — [B-05](USE_CASES_BACKEND.md#b-05-открыть-ws-и-получить-начальное-состояние), [B-18](USE_CASES_BACKEND.md#b-18-обработать-несколько-клиентов), [U-03](USE_CASES_UI.md#u-03-переподключиться-после-разрыва-websocket);
|
||||||
|
4. secondary Brencher — [B-16](USE_CASES_BACKEND.md#b-16-синхронизировать-secondary-brencher), [U-20](USE_CASES_UI.md#u-20-работать-с-secondary-brencher);
|
||||||
|
5. REST contracts, errors и security boundary — [B-01](USE_CASES_BACKEND.md#b-01-получить-состояние-окружений--get-state), [B-02](USE_CASES_BACKEND.md#b-02-получить-доступные-ветки--get-branches), [B-19](USE_CASES_BACKEND.md#b-19-зафиксировать-границу-доступа).
|
||||||
|
|
||||||
|
Отдельное ограничение: `test_containertest.py::test_start` помечен `skip`, поэтому его проверки startup/API не входят в фактически исполняемое покрытие.
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
# Brencher — UI use cases
|
||||||
|
|
||||||
|
## Цель приложения
|
||||||
|
|
||||||
|
Brencher показывает оператору состояние Git-источников и Docker Swarm, позволяет выбрать версию окружения и наблюдать pipeline. Этот файл описывает только пользовательские действия в UI и состояние, которое UI получает от сервера.
|
||||||
|
|
||||||
|
## Канал состояния
|
||||||
|
|
||||||
|
- После открытия страницы UI устанавливает один WebSocket `/ws`.
|
||||||
|
- Сервер присылает `version`, `branches` и `environments`, затем рассылает изменения Jobs/pipeline и окружений.
|
||||||
|
- UI отображает полученное состояние; REST `/state` и `/branches` являются backend read API и не заменяют realtime WebSocket.
|
||||||
|
- Отдельной UI-кнопки rollback в текущей реализации нет.
|
||||||
|
|
||||||
|
## UI use cases
|
||||||
|
|
||||||
|
### U-01. Открыть приложение
|
||||||
|
|
||||||
|
1. Пользователь открывает `/`.
|
||||||
|
2. UI загружает HTML, CSS и JavaScript.
|
||||||
|
3. UI открывает `/ws`.
|
||||||
|
4. На экране появляются версия приложения, список branches, окружения, выбранные коммиты и Jobs.
|
||||||
|
5. Если данных ещё нет, UI показывает loading/пустое состояние.
|
||||||
|
|
||||||
|
### U-02. Получить начальное состояние
|
||||||
|
|
||||||
|
1. После подключения сервер отправляет `version`, `branches` и `environments`.
|
||||||
|
2. UI заменяет loading данными сервера.
|
||||||
|
3. Для каждого окружения отображаются desired branches/commits, deployed commit/version и pipeline status.
|
||||||
|
4. Ошибки окружения показываются как состояние Jobs или error message.
|
||||||
|
|
||||||
|
### U-03. Переподключиться после разрыва WebSocket
|
||||||
|
|
||||||
|
1. Пользователь остаётся на странице при закрытии или ошибке сокета.
|
||||||
|
2. UI показывает disconnected/reconnecting state.
|
||||||
|
3. UI повторяет подключение с задержкой.
|
||||||
|
4. После нового подключения сервер снова присылает initial state.
|
||||||
|
5. При повторных соединениях UI не должен считать старое состояние актуальнее нового; фактические ошибки reconnect видны в логах/статусе.
|
||||||
|
|
||||||
|
### U-04. Просмотреть окружения и deployed state
|
||||||
|
|
||||||
|
1. Пользователь открывает список окружений.
|
||||||
|
2. UI показывает название, selected/desired commit, deployed commit, version, replicas и текущий шаг pipeline, если эти данные прислал сервер.
|
||||||
|
3. Пользователь сравнивает desired и deployed state.
|
||||||
|
4. Недоступное окружение остаётся в списке с ошибкой, а не считается успешно развёрнутым.
|
||||||
|
|
||||||
|
### U-05. Просмотреть branches и remote-контекст
|
||||||
|
|
||||||
|
1. Пользователь открывает выбор branch.
|
||||||
|
2. UI показывает branches, полученные от сервера.
|
||||||
|
3. Одинаковые имена branches разных remotes должны отображаться с контекстом remote.
|
||||||
|
4. После Git fetch сервер присылает обновлённый список, и UI перерисовывает выбор.
|
||||||
|
|
||||||
|
### U-06. Отфильтровать окружения toggle-кнопками
|
||||||
|
|
||||||
|
1. UI показывает toggle-кнопку для каждого доступного окружения/стэка.
|
||||||
|
2. Пользователь включает одну или несколько toggle-кнопок.
|
||||||
|
3. UI оставляет в branches только выбранные окружения.
|
||||||
|
4. UI оставляет в Jobs/pipeline только выбранные окружения.
|
||||||
|
5. Ссылки, статусы и колонки Jobs также относятся только к выбранным окружениям.
|
||||||
|
6. Если все toggle-кнопки выключены, UI показывает все окружения.
|
||||||
|
7. Фильтр меняет только отображение и не изменяет серверное состояние.
|
||||||
|
8. Обновление состояния не должно сбрасывать активный выбор toggle-кнопок, если выбранные окружения всё ещё существуют.
|
||||||
|
9. Если pipeline окружения содержит хотя бы один неуспешный (`error`) или незаконченный (`is_running`) шаг, соответствующая toggle-кнопка получает красную рамку.
|
||||||
|
10. Красная рамка обновляется вместе с состоянием pipeline и не изменяет доступность или поведение toggle-кнопки.
|
||||||
|
|
||||||
|
### U-06a. Отфильтровать окружения текстом
|
||||||
|
|
||||||
|
1. Пользователь вводит текст фильтра.
|
||||||
|
2. UI оставляет подходящие окружения/стэки.
|
||||||
|
3. Фильтр меняет только отображение и не изменяет серверное состояние.
|
||||||
|
4. Очистка фильтра возвращает полный список.
|
||||||
|
|
||||||
|
### U-07. Обновить отображаемое состояние
|
||||||
|
|
||||||
|
1. Пользователь нажимает refresh/update в UI.
|
||||||
|
2. UI отправляет серверу соответствующее WebSocket-сообщение либо ожидает очередное состояние pipeline.
|
||||||
|
3. Сервер присылает branches/environments/jobs.
|
||||||
|
4. UI обновляет строки, статусы и ошибки.
|
||||||
|
5. Автоматического UI-таймера каждые пять минут не следует предполагать; обновление может быть pipeline-driven.
|
||||||
|
|
||||||
|
### U-08. Выбрать branch
|
||||||
|
|
||||||
|
1. Пользователь выбирает branch для окружения.
|
||||||
|
2. UI меняет локальный selection.
|
||||||
|
3. При применении selection отправляется серверу через WebSocket.
|
||||||
|
4. После server update UI отображает выбранное состояние и результат pipeline.
|
||||||
|
|
||||||
|
### U-09. Выбрать `HEAD`
|
||||||
|
|
||||||
|
1. Пользователь выбирает `HEAD` или текущую вершину branch.
|
||||||
|
2. UI показывает этот выбор как desired version.
|
||||||
|
3. При применении сервер разрешает актуальный commit branch.
|
||||||
|
4. Результат checkout/build/deploy и deployed version приходят в Jobs/state.
|
||||||
|
|
||||||
|
### U-10. Выбрать исторический commit
|
||||||
|
|
||||||
|
1. Пользователь открывает историю branch.
|
||||||
|
2. UI показывает доступные commits.
|
||||||
|
3. Пользователь выбирает конкретный commit.
|
||||||
|
4. UI отправляет selection при применении.
|
||||||
|
5. Ошибка отсутствующего commit или merge отображается как ошибка pipeline.
|
||||||
|
|
||||||
|
### U-11. Ввести произвольный commit
|
||||||
|
|
||||||
|
1. Пользователь вводит commit/ref, если такой control доступен.
|
||||||
|
2. UI передаёт значение серверу.
|
||||||
|
3. Сервер проверяет ref/commit и возвращает состояние.
|
||||||
|
4. Неизвестный commit отображается как ошибка, а не как успешная выбранная версия.
|
||||||
|
|
||||||
|
### U-12. Применить выбранное состояние
|
||||||
|
|
||||||
|
1. Пользователь выбирает окружение и версию.
|
||||||
|
2. Нажимает apply/update.
|
||||||
|
3. UI отправляет команду через WebSocket.
|
||||||
|
4. UI показывает queued/running/success/error по сообщениям сервера.
|
||||||
|
5. После завершения показывает selected и deployed state отдельно.
|
||||||
|
|
||||||
|
### U-13. Объединить несколько branches
|
||||||
|
|
||||||
|
1. Пользователь выбирает несколько branches для одного окружения.
|
||||||
|
2. UI отображает состав selection.
|
||||||
|
3. При apply сервер выполняет merge.
|
||||||
|
4. Успешный результат продолжает pipeline; merge conflict отображается в Jobs/error.
|
||||||
|
5. Отдельного обещания автоматического разрешения конфликтов UI не даёт.
|
||||||
|
|
||||||
|
### U-14. Запустить dry run
|
||||||
|
|
||||||
|
1. Пользователь включает dry run.
|
||||||
|
2. UI отправляет selection с dry-run параметром.
|
||||||
|
3. UI показывает Git/analysis/build-preparation progress.
|
||||||
|
4. UI не должен показывать dry run как выполненный deploy.
|
||||||
|
5. Результат и ограничения dry run приходят от сервера; подготовительные шаги могут выполняться до финального запрета deploy.
|
||||||
|
|
||||||
|
### U-15. Наблюдать Jobs и pipeline
|
||||||
|
|
||||||
|
1. Пользователь раскрывает Jobs или строку окружения.
|
||||||
|
2. UI получает и показывает этапы clone, state, checkout/merge, build/workflow, Swarm check и deploy.
|
||||||
|
3. Для текущего шага отображаются progress/status/log message, если они пришли.
|
||||||
|
4. Ошибка останавливает визуальный success flow и остаётся видимой для диагностики.
|
||||||
|
|
||||||
|
### U-16. Просмотреть ссылки сервиса
|
||||||
|
|
||||||
|
1. Сервер присылает `userLinks` в результатах pipeline.
|
||||||
|
2. UI показывает ссылки на приложение/status или связанные сервисы.
|
||||||
|
3. Пользователь открывает ссылку в браузере.
|
||||||
|
4. Если `userLinks` нет, UI не должен придумывать URL.
|
||||||
|
|
||||||
|
### U-17. Увидеть автоматический deploy без действия в UI
|
||||||
|
|
||||||
|
1. Пользователь не нажимает Update.
|
||||||
|
2. Сервер обнаруживает, что remote HEAD отличается от deployed label.
|
||||||
|
3. Сервер запускает pipeline и присылает Jobs/environments update.
|
||||||
|
4. UI отображает changed desired/deployed state и progress.
|
||||||
|
5. Если diff нет, UI не показывает ложный deploy.
|
||||||
|
|
||||||
|
### U-18. Увидеть ошибку Git/credentials/registry/Docker/health check
|
||||||
|
|
||||||
|
1. Пользователь наблюдает Jobs или error panel.
|
||||||
|
2. UI показывает неуспешный шаг и текст ошибки, если он прислан сервером.
|
||||||
|
3. Пользователь устраняет внешнюю причину и повторяет update.
|
||||||
|
4. Наличие error state не считается успешным deploy.
|
||||||
|
|
||||||
|
### U-19. Увидеть stale/conflict state
|
||||||
|
|
||||||
|
1. Два клиента могут выбирать одно или разные окружения одновременно.
|
||||||
|
2. Один клиент может получить состояние, устаревшее относительно другого клиента.
|
||||||
|
3. Сервер может отклонить stale update.
|
||||||
|
4. UI сохраняет локальный выбор до следующего обновления, если сервер не прислал отдельное conflict message.
|
||||||
|
5. Structured conflict dialog текущий backend не гарантирует.
|
||||||
|
|
||||||
|
### U-20. Работать с secondary Brencher
|
||||||
|
|
||||||
|
1. UI получает объединённое состояние локального backend и отдельного secondary Brencher, если `SECONDARY_BRENCHER` настроен.
|
||||||
|
2. Пользователь видит branches/environments обоих источников согласно данным сервера.
|
||||||
|
3. Обрыв secondary-соединения отображается как error/stale state.
|
||||||
|
4. После reconnect UI получает новое initial/update состояние.
|
||||||
|
5. `brencher2` сам по себе является локальным профилем и не означает наличие secondary-сервера.
|
||||||
|
|
||||||
|
### U-21. Просмотреть состояние через прямой REST URL
|
||||||
|
|
||||||
|
1. Пользователь открывает `/state` или `/branches` в браузере/инструменте.
|
||||||
|
2. Сервер возвращает JSON.
|
||||||
|
3. Это read-only диагностика и не заменяет UI-соединение `/ws`.
|
||||||
|
4. Изменение selection через эти GET endpoint-ы не выполняется.
|
||||||
|
|
||||||
|
## Ограничения UI
|
||||||
|
|
||||||
|
- UI не предоставляет отдельного rollback control.
|
||||||
|
- UI не делает постоянное хранилище: после перезапуска backend in-memory state может исчезнуть.
|
||||||
|
- Реальный deploy зависит от Git, credentials, Docker socket, registry, Swarm и настроек pipeline.
|
||||||
|
- В web layer нет встроенной authentication/authorization; безопасность UI должна обеспечиваться внешним reverse proxy или сетью.
|
||||||
|
- Разные профили запускаются через backend configuration; UI отображает только состояние, которое backend прислал.
|
||||||
+72
-10
@@ -13,6 +13,7 @@ const closeStatus = document.getElementById('close-status');
|
|||||||
const refreshBranchesBtn = document.getElementById('refresh-branches');
|
const refreshBranchesBtn = document.getElementById('refresh-branches');
|
||||||
const applyChangesBtn = document.getElementById('apply-changes');
|
const applyChangesBtn = document.getElementById('apply-changes');
|
||||||
const branchFilter = document.getElementById('branch-filter');
|
const branchFilter = document.getElementById('branch-filter');
|
||||||
|
const envFilterToggles = document.getElementById('env-filter-toggles');
|
||||||
const appVersion = document.getElementById('app-version');
|
const appVersion = document.getElementById('app-version');
|
||||||
|
|
||||||
// Branches list (flattened) for UI rendering: [{ envId, envName, branch, commits: [] }]
|
// Branches list (flattened) for UI rendering: [{ envId, envName, branch, commits: [] }]
|
||||||
@@ -21,6 +22,7 @@ let filteredBranches = [];
|
|||||||
|
|
||||||
// Toggle state: show all branches or filtered
|
// Toggle state: show all branches or filtered
|
||||||
let showAllBranches = false;
|
let showAllBranches = false;
|
||||||
|
const activeEnvFilters = new Set();
|
||||||
|
|
||||||
// Environment runtime state storage:
|
// Environment runtime state storage:
|
||||||
// environmentsRaw: array as received from backend: [ [envObj, jobsArr], ... ]
|
// environmentsRaw: array as received from backend: [ [envObj, jobsArr], ... ]
|
||||||
@@ -68,6 +70,7 @@ function checkForPendingChanges() {
|
|||||||
function filterBranches() {
|
function filterBranches() {
|
||||||
const filterText = branchFilter.value.toLowerCase().trim();
|
const filterText = branchFilter.value.toLowerCase().trim();
|
||||||
filteredBranches = branches.filter(({envId, branch, commits}) => {
|
filteredBranches = branches.filter(({envId, branch, commits}) => {
|
||||||
|
if (activeEnvFilters.size > 0 && !activeEnvFilters.has(envId)) return false;
|
||||||
const selList = selectedBranchesByEnv[envId] || [];
|
const selList = selectedBranchesByEnv[envId] || [];
|
||||||
const isSelected = selList.some(([b]) => b === branch);
|
const isSelected = selList.some(([b]) => b === branch);
|
||||||
// Always show branches that appear in any column (e.g. deployed branches from GitUnmerge)
|
// Always show branches that appear in any column (e.g. deployed branches from GitUnmerge)
|
||||||
@@ -86,6 +89,41 @@ function filterBranches() {
|
|||||||
renderBranches();
|
renderBranches();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function environmentHasPipelineProblem(envObj) {
|
||||||
|
return Array.isArray(envObj.pipeline) && envObj.pipeline.some(job =>
|
||||||
|
job && (job.error || job.is_running)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderEnvironmentFilters() {
|
||||||
|
const environments = environmentsRaw
|
||||||
|
.filter(envObj => envObj && (envObj.id || envObj.name))
|
||||||
|
.map(envObj => ({id: envObj.id || envObj.name, name: envObj.name || envObj.id}))
|
||||||
|
.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
const environmentIds = new Set(environments.map(env => env.id));
|
||||||
|
[...activeEnvFilters].forEach(envId => {
|
||||||
|
if (!environmentIds.has(envId)) activeEnvFilters.delete(envId);
|
||||||
|
});
|
||||||
|
envFilterToggles.innerHTML = environments.map(({id, name}) => {
|
||||||
|
const hasPipelineProblem = environmentHasPipelineProblem(
|
||||||
|
environmentsRaw.find(envObj => (envObj.id || envObj.name) === id) || {}
|
||||||
|
);
|
||||||
|
return `
|
||||||
|
<button type="button" class="env-filter-toggle${activeEnvFilters.has(id) ? ' active' : ''}${hasPipelineProblem ? ' has-pipeline-problem' : ''}" data-env="${escapeHtml(id)}" aria-pressed="${activeEnvFilters.has(id)}"${hasPipelineProblem ? ' title="Pipeline has failed or unfinished steps"' : ''}>${escapeHtml(name)}</button>
|
||||||
|
`;
|
||||||
|
}).join('');
|
||||||
|
envFilterToggles.querySelectorAll('.env-filter-toggle').forEach(button => {
|
||||||
|
button.onclick = () => {
|
||||||
|
const envId = button.dataset.env;
|
||||||
|
if (activeEnvFilters.has(envId)) activeEnvFilters.delete(envId);
|
||||||
|
else activeEnvFilters.add(envId);
|
||||||
|
renderEnvironmentFilters();
|
||||||
|
filterBranches();
|
||||||
|
renderJobs();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function getCommitDropdownOptions(envId, branchName, desiredCommit) {
|
function getCommitDropdownOptions(envId, branchName, desiredCommit) {
|
||||||
const branchObj = branches.find(b => b.envId === envId && b.branch === branchName);
|
const branchObj = branches.find(b => b.envId === envId && b.branch === branchName);
|
||||||
let options = '';
|
let options = '';
|
||||||
@@ -156,12 +194,7 @@ function renderBranches() {
|
|||||||
}
|
}
|
||||||
checkForPendingChanges();
|
checkForPendingChanges();
|
||||||
|
|
||||||
const branchesToShow = filteredBranches.length > 0 || branchFilter.value.trim() ? filteredBranches : branches;
|
const branchesToShow = filteredBranches.length > 0 || branchFilter.value.trim() || activeEnvFilters.size > 0 ? filteredBranches : branches;
|
||||||
if (!branchesToShow.length) {
|
|
||||||
branchesList.innerHTML = '<p class="loading">No branches found.</p>';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Group by envId for clearer separation
|
// Group by envId for clearer separation
|
||||||
const groups = branchesToShow.reduce((acc, b) => {
|
const groups = branchesToShow.reduce((acc, b) => {
|
||||||
acc[b.envId] = acc[b.envId] || {envName: b.envName, rows: []};
|
acc[b.envId] = acc[b.envId] || {envName: b.envName, rows: []};
|
||||||
@@ -169,18 +202,30 @@ function renderBranches() {
|
|||||||
return acc;
|
return acc;
|
||||||
}, {});
|
}, {});
|
||||||
|
|
||||||
|
environmentsRaw
|
||||||
|
.filter(envObj => envObj && (activeEnvFilters.size === 0 || activeEnvFilters.has(envObj.id || envObj.name)))
|
||||||
|
.forEach(envObj => {
|
||||||
|
const envId = envObj.id || envObj.name;
|
||||||
|
if (!groups[envId]) groups[envId] = {envName: envObj.name || envId, rows: []};
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!Object.keys(groups).length) {
|
||||||
|
branchesList.innerHTML = '<p class="loading">No branches found.</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
branchesList.innerHTML = Object.entries(groups).map(([envId, {envName, rows}]) => {
|
branchesList.innerHTML = Object.entries(groups).map(([envId, {envName, rows}]) => {
|
||||||
const envCols = columnsByEnv[envId] || {};
|
const envCols = columnsByEnv[envId] || {};
|
||||||
const colNames = Object.keys(envCols);
|
const colNames = Object.keys(envCols);
|
||||||
return `
|
return `
|
||||||
<div class="env-block">
|
<div class="env-block">
|
||||||
<h3 class="env-title">
|
<h3 class="env-title">
|
||||||
Environment: ${envName || envId}
|
Environment: ${escapeHtml(envName || envId)}
|
||||||
<button class="dry-run-btn ${dryRunByEnv[envId] ? 'dry-run-active' : ''}" data-env="${envId}" title="${dryRunByEnv[envId] ? 'Dry run on — click to resume' : 'Running — click to pause (dry run)'}">
|
<button class="dry-run-btn ${dryRunByEnv[envId] ? 'dry-run-active' : ''}" data-env="${envId}" title="${dryRunByEnv[envId] ? 'Dry run on — click to resume' : 'Running — click to pause (dry run)'}">
|
||||||
${dryRunByEnv[envId] ? '▶' : '⏸'}
|
${dryRunByEnv[envId] ? '▶' : '⏸'}
|
||||||
</button>
|
</button>
|
||||||
</h3>
|
</h3>
|
||||||
<table class="branches-table">
|
${rows.length ? `<table class="branches-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>Deploy</th>
|
<th>Deploy</th>
|
||||||
@@ -211,7 +256,7 @@ function renderBranches() {
|
|||||||
</tr>`;
|
</tr>`;
|
||||||
}).join('')}
|
}).join('')}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>` : '<p class="loading">No branches found.</p>'}
|
||||||
</div>`;
|
</div>`;
|
||||||
}).join('');
|
}).join('');
|
||||||
// Event wiring
|
// Event wiring
|
||||||
@@ -283,7 +328,12 @@ function renderJobs() {
|
|||||||
jobsList.innerHTML = '<p class="loading">No jobs found.</p>';
|
jobsList.innerHTML = '<p class="loading">No jobs found.</p>';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
jobsList.innerHTML = environmentsRaw
|
const visibleEnvironments = environmentsRaw.filter(envObj => activeEnvFilters.size === 0 || activeEnvFilters.has(envObj.id || envObj.name));
|
||||||
|
if (visibleEnvironments.length === 0) {
|
||||||
|
jobsList.innerHTML = '<p class="loading">No jobs found.</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
jobsList.innerHTML = visibleEnvironments
|
||||||
.slice()
|
.slice()
|
||||||
.sort((a, b) => (a.name || a.id || '').localeCompare(b.name || b.id || ''))
|
.sort((a, b) => (a.name || a.id || '').localeCompare(b.name || b.id || ''))
|
||||||
.map((envObj) => {
|
.map((envObj) => {
|
||||||
@@ -326,6 +376,7 @@ function renderJobs() {
|
|||||||
const storageKey = 'jobSpoiler:' + key;
|
const storageKey = 'jobSpoiler:' + key;
|
||||||
const safeId = 'spoiler-' + encodeURIComponent(key).replace(/[^a-zA-Z0-9_-]/g, '_');
|
const safeId = 'spoiler-' + encodeURIComponent(key).replace(/[^a-zA-Z0-9_-]/g, '_');
|
||||||
const isError = job.error;
|
const isError = job.error;
|
||||||
|
const isWarning = job.warning;
|
||||||
const isRunning = !!job.is_running;
|
const isRunning = !!job.is_running;
|
||||||
const openByDefault = isError || (window._jobSpoilerState && window._jobSpoilerState[storageKey] === 'open');
|
const openByDefault = isError || (window._jobSpoilerState && window._jobSpoilerState[storageKey] === 'open');
|
||||||
|
|
||||||
@@ -337,6 +388,8 @@ function renderJobs() {
|
|||||||
? `<span class="step-spinner" title="Running"></span>`
|
? `<span class="step-spinner" title="Running"></span>`
|
||||||
: isError
|
: isError
|
||||||
? `<span style="color:#dc3545;font-weight:bold;margin-right:6px;" title="Error">!</span>`
|
? `<span style="color:#dc3545;font-weight:bold;margin-right:6px;" title="Error">!</span>`
|
||||||
|
: isWarning
|
||||||
|
? `<span style="color:#d99700;font-weight:bold;margin-right:6px;" title="Warning">⚠</span>`
|
||||||
: `<span style="color:#28a745;font-weight:bold;margin-right:6px;" title="OK">✔</span>`}
|
: `<span style="color:#28a745;font-weight:bold;margin-right:6px;" title="OK">✔</span>`}
|
||||||
${envObj.id} - ${job.name}
|
${envObj.id} - ${job.name}
|
||||||
</div>
|
</div>
|
||||||
@@ -426,6 +479,7 @@ function setupWebSockets() {
|
|||||||
const data = message.environments;
|
const data = message.environments;
|
||||||
payload = data || {};
|
payload = data || {};
|
||||||
environmentsRaw = Object.values(payload);
|
environmentsRaw = Object.values(payload);
|
||||||
|
renderEnvironmentFilters();
|
||||||
|
|
||||||
// Sync selections and column data per environment
|
// Sync selections and column data per environment
|
||||||
environmentsRaw.forEach((envObj) => {
|
environmentsRaw.forEach((envObj) => {
|
||||||
@@ -532,6 +586,14 @@ function updateEnvironment() {
|
|||||||
showStatus('Changes applied (pending server confirmation).');
|
showStatus('Changes applied (pending server confirmation).');
|
||||||
}
|
}
|
||||||
// Initial load
|
// Initial load
|
||||||
|
(function applyUrlFilter() {
|
||||||
|
const params = new URLSearchParams(window.location.search);
|
||||||
|
const initialFilter = params.get('filter');
|
||||||
|
if (initialFilter && branchFilter) {
|
||||||
|
branchFilter.value = initialFilter;
|
||||||
|
filterBranches();
|
||||||
|
}
|
||||||
|
})();
|
||||||
setupWebSockets();
|
setupWebSockets();
|
||||||
showStatus('Loading branches...');
|
showStatus('Loading branches...');
|
||||||
renderBranches();
|
renderBranches();
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
<input type="text" id="branch-filter"
|
<input type="text" id="branch-filter"
|
||||||
placeholder="Filter branches by name, commit ID, or commit message..." class="filter-input">
|
placeholder="Filter branches by name, commit ID, or commit message..." class="filter-input">
|
||||||
</div>
|
</div>
|
||||||
|
<div id="env-filter-toggles" class="env-filter-toggles" aria-label="Environment filters"></div>
|
||||||
<div class="control-bar" style="float: left;">
|
<div class="control-bar" style="float: left;">
|
||||||
<button id="toggle-show-all" class="toggle-button">Show All</button>
|
<button id="toggle-show-all" class="toggle-button">Show All</button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -136,6 +136,35 @@ body {
|
|||||||
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
|
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.env-filter-toggles {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
clear: both;
|
||||||
|
padding: 8px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.env-filter-toggle {
|
||||||
|
background: #fff;
|
||||||
|
color: #495057;
|
||||||
|
border: 1px solid #adb5bd;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 8px 14px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.env-filter-toggle:hover,
|
||||||
|
.env-filter-toggle.active {
|
||||||
|
background: #007bff;
|
||||||
|
color: #fff;
|
||||||
|
border-color: #007bff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.env-filter-toggle.has-pipeline-problem {
|
||||||
|
border: 2px solid #dc3545;
|
||||||
|
}
|
||||||
|
|
||||||
/* Branches table styling */
|
/* Branches table styling */
|
||||||
.branches-table {
|
.branches-table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
|||||||
@@ -11,3 +11,7 @@ types-PyYAML
|
|||||||
types-requests
|
types-requests
|
||||||
types-docker
|
types-docker
|
||||||
testcontainers
|
testcontainers
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ These tests run in a Docker-like isolated environment to avoid harming the host
|
|||||||
They simulate remote and local git repositories and test various merge scenarios.
|
They simulate remote and local git repositories and test various merge scenarios.
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
|
||||||
import git
|
import git
|
||||||
import pytest
|
import pytest
|
||||||
from steps.git import CheckoutAndMergeResult, GitUnmergeResult
|
from steps.git import CheckoutAndMergeResult, GitClone, GitUnmergeResult
|
||||||
|
|
||||||
from .test_remote_repo import RemoteRepoHelper
|
from .test_remote_repo import RemoteRepoHelper
|
||||||
|
|
||||||
@@ -16,6 +18,123 @@ from .test_remote_repo import RemoteRepoHelper
|
|||||||
class TestGitIntegration:
|
class TestGitIntegration:
|
||||||
"""Integration tests for git operations"""
|
"""Integration tests for git operations"""
|
||||||
|
|
||||||
|
def test_git_clone_multiple_urls(self, repo_helper: RemoteRepoHelper) -> None:
|
||||||
|
repo_helper.create_commit(repo_helper.repo, "master", "master", "README.md", "content", "Initial commit")
|
||||||
|
second_url = f"file://{repo_helper.remote_dir}"
|
||||||
|
clone = GitClone(url=[repo_helper.remote_dir, second_url])
|
||||||
|
clone.env = repo_helper.env
|
||||||
|
|
||||||
|
repo_path = clone.progress()
|
||||||
|
repo = git.Repo(repo_path)
|
||||||
|
|
||||||
|
assert {remote.name for remote in repo.remotes} == {"origin", "repo1"}
|
||||||
|
assert repo.remotes.origin.url == repo_helper.remote_dir
|
||||||
|
assert repo.remotes.repo1.url == second_url
|
||||||
|
assert set(clone.get_branches()) == {"master", "repo1/master"}
|
||||||
|
|
||||||
|
def test_git_clone_filters_auto_branches(self, repo_helper: RemoteRepoHelper) -> None:
|
||||||
|
repo_helper.create_commit(repo_helper.repo, "master", "master", "README.md", "content", "Initial commit")
|
||||||
|
repo_helper.create_commit(repo_helper.repo, "master", "feature", "feature.txt", "feature", "Feature commit")
|
||||||
|
repo_helper.create_commit(repo_helper.repo, "master", "auto-abc12345", "auto.txt", "auto", "Auto commit")
|
||||||
|
|
||||||
|
clone = GitClone(url=repo_helper.remote_dir)
|
||||||
|
clone.env = repo_helper.env
|
||||||
|
clone.progress()
|
||||||
|
|
||||||
|
assert set(clone.get_branches()) == {"master", "feature"}
|
||||||
|
|
||||||
|
def test_git_clone_named_remotes(self, repo_helper: RemoteRepoHelper) -> None:
|
||||||
|
# Two real local repos served as separate "remotes". The user controls
|
||||||
|
# their names explicitly via the `remotes=[{name,url}]` API.
|
||||||
|
def fresh_repo(prefix: str, message: str) -> str:
|
||||||
|
path = tempfile.mkdtemp(prefix=prefix)
|
||||||
|
repo = git.Repo.init(path, bare=False)
|
||||||
|
with repo.config_writer() as cw:
|
||||||
|
cw.set_value("user", "email", "test@example.com")
|
||||||
|
cw.set_value("user", "name", "Test User")
|
||||||
|
repo_helper.create_commit(repo, "master", "master", "README.md", "content", message)
|
||||||
|
return path
|
||||||
|
|
||||||
|
github_dir = fresh_repo("test_named_github_", "github initial")
|
||||||
|
gitea_dir = fresh_repo("test_named_gitea_", "gitea initial")
|
||||||
|
try:
|
||||||
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "github", "url": github_dir},
|
||||||
|
{"name": "gitea_admin", "url": gitea_dir},
|
||||||
|
])
|
||||||
|
clone.env = repo_helper.env
|
||||||
|
|
||||||
|
repo_path = clone.progress()
|
||||||
|
repo = git.Repo(repo_path)
|
||||||
|
|
||||||
|
# User-chosen names appear exactly; the auto-generated "origin" /
|
||||||
|
# "repo1" names from the positional-list form do NOT leak in.
|
||||||
|
assert {r.name for r in repo.remotes} == {"github", "gitea_admin"}
|
||||||
|
assert "origin" not in repo.remotes
|
||||||
|
assert "repo1" not in repo.remotes
|
||||||
|
assert repo.remotes.github.url == github_dir
|
||||||
|
assert repo.remotes.gitea_admin.url == gitea_dir
|
||||||
|
|
||||||
|
# `get_branches` keeps the <remote>/<branch> shape for non-origin
|
||||||
|
# names; the user gets the full provenance in the key.
|
||||||
|
assert set(clone.get_branches()) == {"github/master", "gitea_admin/master"}
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(github_dir, ignore_errors=True)
|
||||||
|
shutil.rmtree(gitea_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
def test_git_clone_keeps_available_remote_when_another_is_unreachable(self, repo_helper: RemoteRepoHelper) -> None:
|
||||||
|
repo_helper.create_commit(repo_helper.repo, "master", "master", "README.md", "content", "Initial commit")
|
||||||
|
clone = GitClone(remotes=[
|
||||||
|
{"name": "available", "url": repo_helper.remote_dir},
|
||||||
|
{"name": "unreachable", "url": "/does/not/exist"},
|
||||||
|
])
|
||||||
|
clone.env = repo_helper.env
|
||||||
|
|
||||||
|
clone.progress()
|
||||||
|
|
||||||
|
assert "available/master" in clone.get_branches()
|
||||||
|
assert len(clone.errors) == 1
|
||||||
|
assert "unreachable" in clone.errors[0]
|
||||||
|
|
||||||
|
def test_git_clone_keeps_empty_repository_when_all_remotes_are_unreachable(self, repo_helper: RemoteRepoHelper) -> None:
|
||||||
|
clone = GitClone(url="/does/not/exist")
|
||||||
|
clone.env = repo_helper.env
|
||||||
|
|
||||||
|
repo_path = clone.progress()
|
||||||
|
|
||||||
|
assert os.path.isdir(os.path.join(repo_path, ".git"))
|
||||||
|
assert clone.get_branches() == {}
|
||||||
|
|
||||||
|
def test_git_clone_remotes_validation(self) -> None:
|
||||||
|
# Empty list: rejected (would produce an unusable clone).
|
||||||
|
with pytest.raises(ValueError, match="At least one repository URL is required"):
|
||||||
|
GitClone(remotes=[])
|
||||||
|
|
||||||
|
# Missing / empty / non-string name or url: rejected.
|
||||||
|
with pytest.raises(ValueError, match="non-empty 'name'"):
|
||||||
|
GitClone(remotes=[{"url": "git@example.com:foo/bar.git"}])
|
||||||
|
with pytest.raises(ValueError, match="non-empty 'name'"):
|
||||||
|
GitClone(remotes=[{"name": "", "url": "git@example.com:foo/bar.git"}])
|
||||||
|
with pytest.raises(ValueError, match="non-empty 'url'"):
|
||||||
|
GitClone(remotes=[{"name": "github"}])
|
||||||
|
with pytest.raises(ValueError, match="non-empty 'url'"):
|
||||||
|
GitClone(remotes=[{"name": "github", "url": ""}])
|
||||||
|
|
||||||
|
# Duplicate name: rejected.
|
||||||
|
with pytest.raises(ValueError, match="Duplicate remote name"):
|
||||||
|
GitClone(remotes=[
|
||||||
|
{"name": "github", "url": "git@example.com:a/b.git"},
|
||||||
|
{"name": "github", "url": "git@example.com:c/d.git"},
|
||||||
|
])
|
||||||
|
|
||||||
|
# Passing both `url` and `remotes`: rejected.
|
||||||
|
with pytest.raises(ValueError, match="not both"):
|
||||||
|
GitClone(url="git@example.com:a/b.git", remotes=[{"name": "github", "url": "git@example.com:a/b.git"}])
|
||||||
|
|
||||||
|
# Passing neither: rejected.
|
||||||
|
with pytest.raises(ValueError, match="requires either 'url' or 'remotes'"):
|
||||||
|
GitClone()
|
||||||
|
|
||||||
def test_checkout_merged_one_branch(self, repo_helper: RemoteRepoHelper) -> None:
|
def test_checkout_merged_one_branch(self, repo_helper: RemoteRepoHelper) -> None:
|
||||||
# Create main branch with initial commit
|
# Create main branch with initial commit
|
||||||
commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1",
|
commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1",
|
||||||
@@ -251,6 +370,15 @@ class TestGitIntegration:
|
|||||||
with pytest.raises(BaseException, match="Version format not recognized"):
|
with pytest.raises(BaseException, match="Version format not recognized"):
|
||||||
repo_helper.git_unmerge.progress()
|
repo_helper.git_unmerge.progress()
|
||||||
|
|
||||||
|
def test_git_unmerge_empty_version_uses_default_branch(self, repo_helper: RemoteRepoHelper) -> None:
|
||||||
|
repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content", "Initial commit")
|
||||||
|
repo_helper.set_desired_branches([])
|
||||||
|
repo_helper.mock_check.version = lambda: "" # type: ignore[attr-defined]
|
||||||
|
|
||||||
|
result = repo_helper.git_unmerge.progress()
|
||||||
|
|
||||||
|
assert result.branches == [()]
|
||||||
|
|
||||||
def test_git_unmerge_nonhead_commit(self, repo_helper: RemoteRepoHelper) -> None:
|
def test_git_unmerge_nonhead_commit(self, repo_helper: RemoteRepoHelper) -> None:
|
||||||
# Create initial commit
|
# Create initial commit
|
||||||
commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1",
|
commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1",
|
||||||
|
|||||||
Reference in New Issue
Block a user