diff --git a/.gitignore b/.gitignore index 22da011..3b15b21 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ env/ .env .env.* !.env.example +.gitlab.variables.env data/*.sqlite3 data/*.db diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4842e8b..1b86258 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,8 +1,10 @@ stages: - build + - deploy variables: - DOCKER_IMAGE: $DOCKER_REGISTRY/belki:latest + DOCKER_IMAGE_REPOSITORY: $DOCKER_REGISTRY/cwshed-clone/belki + KUBE_NAMESPACE: belki DOCKER_HOST: tcp://docker:2375 build: stage: build @@ -18,10 +20,44 @@ build: # Docker Registry - echo "$DOCKER_PASSWORD" | docker login $DOCKER_REGISTRY -u "$DOCKER_USERNAME" --password-stdin - # Docker build over dind - - docker build -t $DOCKER_IMAGE . + - export IMAGE_TAG="$CI_COMMIT_SHORT_SHA" + - docker build --pull -t "$DOCKER_IMAGE_REPOSITORY:$IMAGE_TAG" -t "$DOCKER_IMAGE_REPOSITORY:latest" . + - docker push "$DOCKER_IMAGE_REPOSITORY:$IMAGE_TAG" + - docker push "$DOCKER_IMAGE_REPOSITORY:latest" + rules: + - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' - # Push the resulting image - - docker push $DOCKER_IMAGE - only: - - main +deploy: + stage: deploy + image: bitnami/kubectl:1.34 + needs: [build] + rules: + - if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' + before_script: + - test -n "$KUBE_CONFIG_B64" + - test -n "$VK_GROUP_TOKEN" + - test -n "$VK_GROUP_ID" + - test -n "$BELKI_DATABASE_URL" + - test -n "$POSTGRES_PASSWORD" + - test -n "$BELKI_ADMIN_PASSWORD" + - mkdir -p "$CI_PROJECT_DIR/.kube" + - printf '%s' "$KUBE_CONFIG_B64" | base64 -d > "$CI_PROJECT_DIR/.kube/config" + - export KUBECONFIG="$CI_PROJECT_DIR/.kube/config" + - kubectl version --client + - kubectl -n "$KUBE_NAMESPACE" get serviceaccount gitlab-deploy + script: + - kubectl -n "$KUBE_NAMESPACE" create secret generic belki-runtime + --from-literal=VK_GROUP_TOKEN="$VK_GROUP_TOKEN" + --from-literal=VK_GROUP_ID="$VK_GROUP_ID" + --from-literal=VK_API_VERSION="${VK_API_VERSION:-5.199}" + --from-literal=BELKI_DATABASE_URL="$BELKI_DATABASE_URL" + --from-literal=POSTGRES_PASSWORD="$POSTGRES_PASSWORD" + --from-literal=BELKI_ADMIN_PASSWORD="$BELKI_ADMIN_PASSWORD" + --dry-run=client -o yaml | kubectl apply -f - + - sed "s#reg.nyan404.ru/cwshed-clone/belki:6b74dfa#$DOCKER_IMAGE_REPOSITORY:$CI_COMMIT_SHORT_SHA#g" deploy/k8s/production.yaml | kubectl apply -f - + - kubectl -n "$KUBE_NAMESPACE" rollout status deployment/belki-postgres --timeout=180s + - kubectl -n "$KUBE_NAMESPACE" rollout status deployment/belki-web --timeout=180s + - kubectl -n "$KUBE_NAMESPACE" rollout status deployment/belki-bot --timeout=180s + - kubectl -n "$KUBE_NAMESPACE" get pods,svc + after_script: + - rm -rf "$CI_PROJECT_DIR/.kube" diff --git a/AGENTS.md b/AGENTS.md index f1f11df..6ca3575 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,15 +7,16 @@ ## Working Rules - Keep the calculation domain independent from HTTP, VK, and Kubernetes. - Keep VK tokens and group IDs out of the repository; use environment variables or Kubernetes Secrets. -- Do not apply `deploy/k8s/` until the bot commands, report wording, registry image name, service exposure, and Secret handoff are explicitly confirmed. +- Production manifests are already applied in namespace `belki`; CI deploys them from `main` using the namespace-scoped RBAC in [`deploy/k8s/rbac.yaml`](./deploy/k8s/rbac.yaml). - Prefer `docker:dind` for CI unless the target runner is explicitly pinned and known to expose `/var/run/docker.sock`. ## Validation - For CI-only changes, prefer a targeted YAML parse and a diff review. - For image/runtime changes, check the `Dockerfile`, Python entrypoint, static asset serving, and CI job together. -- For k3s changes, validate YAML and current cluster inventory first; deployment is currently deferred. +- For k3s changes, validate YAML and current cluster inventory first; keep `KUBE_CONFIG_B64` masked/protected in GitLab. - Do not add unnecessary local build artifacts or temporary files to the repository. ## Notes - `docker:dind` requires a privileged Docker executor and `DOCKER_HOST=tcp://docker:2375` with `DOCKER_TLS_CERTDIR=""`. - The `dind` daemon can take time to initialize; this repo waits for `docker info` before building. +- Never commit `.env` or `.gitlab.variables.env`; the latter contains the GitLab Variable handoff and a namespace-scoped kubeconfig. diff --git a/MEMORY.md b/MEMORY.md index deabac7..d846bfd 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -20,3 +20,4 @@ - The admin history is served at `/admin`; `/api/admin/calculations` requires `BELKI_ADMIN_PASSWORD` via `X-Admin-Password` and supports sorting by kitten ID/name. The password is configured out-of-band and is not stored in browser localStorage. - The new domain uses 5 minutes = 1 adult point and 5 minutes = 2 kitten points; a non-self-sufficient main kitten gives the adult a 1.5x multiplier and each additional non-self-sufficient kitten adds 0.5x, matching the inspected Google Sheet formulas. - 2026-08-16 production deployment: namespace `belki` is live in k3s. Web and bot use `reg.nyan404.ru/cwshed-clone/belki:6b74dfa`; PostgreSQL uses the amd64 mirror `reg.nyan404.ru/library/postgres:16-alpine-amd64` on Longhorn. The web LoadBalancer is MetalLB `10.12.0.212`; route `cat.nyan404.ru/belki` through the external Nginx to that IP. Runtime credentials remain only in the cluster Secret `belki-runtime`. +- GitLab CI/CD now builds SHA/latest tags and deploys `deploy/k8s/production.yaml` from `main`. The ignored `.gitlab.variables.env` is a local handoff for GitLab Variables; CI uses namespace-scoped ServiceAccount `belki/gitlab-deploy`, not cluster-admin credentials. diff --git a/deploy/k8s/rbac.yaml b/deploy/k8s/rbac.yaml new file mode 100644 index 0000000..eca309b --- /dev/null +++ b/deploy/k8s/rbac.yaml @@ -0,0 +1,43 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: gitlab-deploy + namespace: belki +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: gitlab-deploy + namespace: belki +rules: + - apiGroups: [""] + resources: + - configmaps + - events + - persistentvolumeclaims + - pods + - pods/log + - secrets + - services + verbs: [get, list, watch, create, update, patch] + - apiGroups: ["apps"] + resources: + - deployments + - deployments/status + - replicasets + - replicasets/status + verbs: [get, list, watch, create, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: gitlab-deploy + namespace: belki +subjects: + - kind: ServiceAccount + name: gitlab-deploy + namespace: belki +roleRef: + kind: Role + name: gitlab-deploy + apiGroup: rbac.authorization.k8s.io diff --git a/deploy/k8s/secret.example.yaml b/deploy/k8s/secret.example.yaml index de84559..3c3edad 100644 --- a/deploy/k8s/secret.example.yaml +++ b/deploy/k8s/secret.example.yaml @@ -1,7 +1,7 @@ apiVersion: v1 kind: Secret metadata: - name: belki-vk + name: belki-runtime namespace: belki type: Opaque stringData: @@ -9,4 +9,5 @@ stringData: VK_GROUP_ID: replace-out-of-band VK_API_VERSION: "5.199" BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki + POSTGRES_PASSWORD: replace-out-of-band BELKI_ADMIN_PASSWORD: replace-out-of-band diff --git a/docs/GITLAB_CI_CD.md b/docs/GITLAB_CI_CD.md new file mode 100644 index 0000000..5aa26cf --- /dev/null +++ b/docs/GITLAB_CI_CD.md @@ -0,0 +1,44 @@ +# GitLab CI/CD для «Беличьей норы» + +`.gitlab-ci.yml` выполняет два шага на `main`: + +1. Собирает образ и публикует его в `reg.nyan404.ru/cwshed-clone/belki` с тегами короткого SHA и `latest`. +2. Подключается к k3s namespace `belki`, обновляет runtime Secret, применяет `deploy/k8s/production.yaml` и ждёт готовности web, bot и PostgreSQL. + +## Переменные GitLab + +Файл `.gitlab.variables.env` рядом с локальным `.env` содержит подготовленные значения для текущего окружения. Он игнорируется Git и имеет права `0600`; его нельзя коммитить или пересылать в открытом виде. + +Добавьте в GitLab → Settings → CI/CD → Variables: + +| Переменная | Назначение | Защита | +| --- | --- | --- | +| `DOCKER_REGISTRY` | `reg.nyan404.ru` | masked, protected | +| `DOCKER_USERNAME` | пользователь registry | masked, protected | +| `DOCKER_PASSWORD` | пароль registry | masked, protected | +| `DOCKER_IMAGE_REPOSITORY` | `reg.nyan404.ru/cwshed-clone/belki` | protected | +| `KUBE_NAMESPACE` | `belki` | protected | +| `KUBE_CONFIG_B64` | base64 kubeconfig для ServiceAccount `gitlab-deploy` | masked, protected | +| `VK_GROUP_TOKEN` | токен VK-группы | masked, protected | +| `VK_GROUP_ID` | ID VK-группы | protected | +| `VK_API_VERSION` | обычно `5.199` | protected | +| `BELKI_DATABASE_URL` | DSN PostgreSQL внутри k3s | masked, protected | +| `POSTGRES_PASSWORD` | пароль PostgreSQL | masked, protected | +| `BELKI_ADMIN_PASSWORD` | пароль `/admin` | masked, protected | + +`KUBE_CONFIG_B64` уже ограничен namespace `belki`: CI использует отдельные `ServiceAccount`, `Role` и `RoleBinding` из [`deploy/k8s/rbac.yaml`](../deploy/k8s/rbac.yaml), а не кластерный admin-доступ. + +При смене токена VK или паролей достаточно обновить соответствующие GitLab Variables: deploy-job применит `belki-runtime` заново. Для изменения PostgreSQL-пароля существующей базы потребуется отдельная процедура, поскольку пароль уже хранится внутри кластера. + +## Ручная проверка + +Для проверки без CI используйте тот же kubeconfig и манифест: + +```sh +export KUBECONFIG=/path/to/kubeconfig +kubectl -n belki apply -f deploy/k8s/rbac.yaml +kubectl -n belki apply -f deploy/k8s/production.yaml +kubectl -n belki rollout status deployment/belki-web --timeout=180s +``` + +MetalLB адрес web-сервиса — `10.12.0.212`; внешний Nginx проксирует на него путь `cat.nyan404.ru/belki`. diff --git a/structure_and_data.md b/structure_and_data.md index 96320e6..78360c3 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -5,7 +5,8 @@ - [`Dockerfile`](./Dockerfile): Python 3.12 runtime image for the calculator web service and shared static assets. - [`app/`](./app): calculation domain, report templates, JSON API, HTTP server, and VK Bots Long Poll adapter. - [`web/`](./web): calculator frontend plus legacy CatWar userscript assets. -- [`deploy/k8s/`](./deploy/k8s): namespace and production web/bot/PostgreSQL manifests. +- [`deploy/k8s/`](./deploy/k8s): namespace, production web/bot/PostgreSQL manifests, and namespace-scoped CI deploy RBAC. +- [`docs/GITLAB_CI_CD.md`](./docs/GITLAB_CI_CD.md): GitLab variables and CI/CD handoff. - [`tests/`](./tests): standard-library unit tests for calculation, reports, API, and VK parsing. - [`docs/staging/`](./docs/staging): working specification and implementation plan for the Belki calculator. - [`AGENTS.md`](./AGENTS.md): repo-specific instructions for future coding agents. @@ -39,3 +40,4 @@ - 2026-08-16: made bulk entry conversational and separator-free; added API/web inspection and clarification flow. - 2026-08-16: rewrote VK help, welcome, and web hints as a concise neutral FAQ; command behavior is unchanged. - 2026-08-16: added the calculator/VK links to the CatWar home page and deployed the calculator stack to k3s; MetalLB assigned `10.12.0.212`. +- 2026-08-16: added GitLab build/deploy stages, namespace-scoped `gitlab-deploy` RBAC, and the ignored local variables handoff `.gitlab.variables.env`.