diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9dbed3c..c356e70 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,9 +14,22 @@ name: CI +# TETIKLEYICILER -- main push'u BURADA DEGIL `main.yml`'de kosar. +# +# Push'ta ayni kapi iki kez kosmasin diye main dali buradan DISLANIR: +# +# * `main` push'u -> `main.yml` (ayni bes katman + Build and test + Deploy); +# * diger dallara push ve TUM pull_request'ler -> burasi (asagidaki +# katmanlarin tamami); +# * elle kosum -> burasi. +# +# Katmanlar iki dosyada ayri ayri durur cunku `main.yml`'de her push'ta kosar +# ve deploy'u kapilar; burasi ise dala/PR'a hizli geri bildirim verir. Ikisinin +# komutlari AYNIDIR (tek dogruluk kaynagi: scripts/ci-yerel.sh); birini +# degistirirken digerini de degistirin. on: push: - branches: ["**"] + branches-ignore: ["main"] pull_request: workflow_dispatch: @@ -152,19 +165,29 @@ jobs: # Iki yonlu denetim: (1) zorunlu env YOKKEN `config` PATLAMALI, # (2) VARKEN gecerli bir yapilandirma uretmeli. Yalnizca ikincisini # denetlemek, `${VAR:?}` yerine `${VAR:-}` yazilmasini yakalamaz. + # + # ZORUNLU SIRLAR LISTESI compose.yaml'IN KENDISINDEN OKUNUR: ucuncu + # sir `ZEKA_PG_DSN` (compose.yaml:82) eklendiginde bu adim ve yerel + # esdegeri `scripts/ci-compose.sh` iki sirla kalmis, adim "sirlar + # verilse bile patliyor" diyerek KIRMIZI kalmisti. Liste artik tamdir; + # compose.yaml'a sir eklerken burayi da guncelleyin (ve + # scripts/ci-compose.sh'i; yerel esdeger AYNI kapi olmali). working-directory: service run: | echo "--- zorunlu env eksikken patlamali ---" - if docker compose config >/dev/null 2>&1; then - echo "HATA: AI_SHARED_TOKEN/DEEPSEEK_API_KEY olmadan gecti;" + if env -u AI_SHARED_TOKEN -u DEEPSEEK_API_KEY -u ZEKA_PG_DSN \ + docker compose config >/dev/null 2>&1; then + echo "HATA: zorunlu sirlar olmadan gecti;" echo " zorunlu sirlar \${VAR:?} bicimini kaybetmis olabilir." exit 1 fi echo "ok: zorunlu env olmadan reddedildi" echo "--- zorunlu env varken gecerli olmali ---" - AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte docker compose config + AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte \ + ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci docker compose config echo "--- port ACILMAMALI (disa arama servisi) ---" - if AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte docker compose config \ + if AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte \ + ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci docker compose config \ | grep -qE '^\s+ports:'; then echo "HATA: compose port aciyor; ZEKA backend'e dial-out eder, port ACMAZ." exit 1 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..87586dd --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,611 @@ +# VPS deploy -- ZEKA kopru servisi. Sekil, ailedeki Celebi/RAG deploy'uyla +# AYNI (hata toparlama ucuz olsun): +# +# Katman 1..5 -- ci.yml'deki BES katmanin KENDISI; push'ta burada kosar. +# Komutlar oradakiyle birebir aynidir (tek dogruluk +# kaynagi: scripts/ci-yerel.sh). +# Build and test -- bes katman yesilse imaji derler ve kosunun artefaktini +# (imaj tarball'i + compose.yaml + systemd unit'i + tag) +# yukler. Ad BILEREK "Build and test": workflow_dispatch +# yolu en yeni yesil kosuyu tam bu ISIN ADIYLA arar +# (`gh run view ... select(.name=="Build and test")`). +# Deploy -- SSH: kapasite on kontrolu, imaji yukle, deploy sahipli +# stack.env'in HEZARFEN_TAG'ini ona cevir, compose.yaml + +# unit'i kur, stack'i yeniden baslat, servisin KENDI +# saglik betigiyle dogrula, olmazsa onceki tag'e don, +# ardindan bagimsiz dogrulama. +# +# KATMANLAR NEDEN AYRI ISLER -- gerekce ci.yml'in basindan aynen: +# "Katmanlar bilincli olarak AYRI islerdir, tek bir dev is degil: bir kosucu +# konteyner derleyemiyorsa testler yine de kosar, ve sozlesme denetimi +# kirildiginda 'testler gecti ama sozlesme kaldi' bilgisi tek bakista +# gorunur." +# Push'ta ayni kapi IKI KEZ kosmasin diye ci.yml'in push tetikleyicisi main +# dalini DISLAR (bkz. ci.yml `on:`): main push'u boylece tam olarak bir kez +# kosar; diger dallar ve PR'lar katmanlari ci.yml'den alir. +# +# YESIL BIR MAIN PUSH'U OTOMATIK DAGITIR (Celebi'nin sekli; RAG'da dagitim +# bilerek elleydi cunku orada ~4,5 GB model ve GPU'suz makinede gecmeyen bir +# urun kapisi var -- ZEKA hafif bir koprudur, o gerekce burada yok). +# +# Elle yeniden dagitim -- Actions -> Run workflow, ya da: +# gh workflow run main.yml --ref main +# Bu yol suiti TEKRAR kosmaz: "Build and test" isi yesil olan en yeni kosunun +# artefaktini dagitir (asagidaki "Find the newest green build" adimi). +# +# Bir seferlik on kosullar (workflow'un erisimi disinda): +# * repo secret'lari SSH_PRIVATE_KEY / SSH_HOST / SSH_USER -- backend ve +# frontend deploy'unun kullandigi uc isim; +# * sunucuda `loginctl enable-linger ` (kullanici unit'leri icin); +# * sunucuda podman + bir compose saglayici (deploy ikisini de kontrol eder); +# * operatorun ~/hezarfen_zeka/hezarfen_zeka.env dosyasi (0600; sablon: +# deploy/hezarfen_zeka.env.example). Deploy onu ASLA olusturmaz, yazmaz; +# yalniz varligini kontrol eder ve iznini 0600'e ceker; +# * backend tarafi acik olmali: hezarfen_backend.env icinde +# AI_QUIC_ADDR=0.0.0.0:8090 ve AI_SHARED_TOKEN bu koprununkiyle AYNI. +# Bu bir KAPI DEGILDIR -- asagida gerekcesiyle yazilidir. + +name: VPS deploy + +on: + push: + branches: + - main + # Elle yeniden deploy kapisi -- yukaridaki baslik yorumuna bakin. + workflow_dispatch: + +# Deploy serilestirmesi workflow'da degil deploy isinde: yeni bir push, ucustaki +# VPS degisimine dokunmadan bayat katman/Build kosularini iptal edebilmeli. +permissions: + contents: read + # workflow_dispatch yolu `gh run list/view` ile en yeni yesil kosuyu arar ve o + # kosunun artefaktini indirir; ikisi de Actions API'sidir ve YAZMA GEREKMEZ. + actions: read + +env: + # systemd kullanici unit'i. Bkz. deploy/hezarfen_zeka_compose.service. + SERVICE: hezarfen_zeka_compose + # Deploy, SSH kullanicisinin home'u altindaki bu alt dizinde yasar ($HOME + # sunucuda cozulur). + DEPLOY_SUBDIR: hezarfen_zeka + # Operatorun ayar dosyasi; deploy yalniz varligini kontrol eder, yazmaz. + ENV_FILE_NAME: hezarfen_zeka.env + # compose.yaml'daki `container_name` (bkz. service/compose.yaml:11). + CONTAINER_NAME: hezarfen-zeka-bridge + # Saglik kapisinin on kosulu: backend'in HTTP sertifika ucu. Backend'in host + # loopback portu (README: `127.0.0.1:7656:7656`). + CERT_PATH: /ai/certificate + BACKEND_HTTP_PORT: "7656" + +jobs: + # ========================================================================= + # KATMAN 1..5 -- ci.yml'deki bes katman. Adlar, adim metinleri ve komutlar + # oradan BIREBIR tasindi; burada degisen tek sey `if` ve `concurrency`: + # dispatch bu suiti tekrar odemez (bkz. dosya basi). + # ========================================================================= + sozdizimi: + name: "Katman 1 -- sozdizimi (her .py ayristirilabiliyor mu)" + if: github.event_name == 'push' + concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }}-sozdizimi + cancel-in-progress: true + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: "Butun kaynaklar ayristirilabiliyor mu" + # Testlerden ONCE kosar: bozuk bir dosya, testlerin toplanmasini + # engelleyip anlamsiz bir toplama hatasi uretir. Burada hangi dosya + # ve hangi satir oldugu tek satirda gorunur. + run: | + python -m compileall -q -x '(__pycache__|\.venv|venv)' \ + service/src service/tests scripts + + # ========================================================================= + testler: + name: "Katman 2 -- birim testleri (saf unittest, bagimliliksiz)" + if: github.event_name == 'push' + concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }}-testler + cancel-in-progress: true + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: "python -m unittest discover" + # BAGIMLILIK KURULMAZ. Bu kasitli: test paketi saf `unittest` + # kullanir ve `requirements.txt` gerektirmez. Boylece bu is, + # bagimlilik cozumleme sorunlarindan BAGIMSIZ olarak kirmizi/yesil + # bilgisi verir; ag kesintisi testleri dusuremez. + # + # `aioquic` gerektiren canli kopru testleri kendiliginden ATLANIR + # (tests/test_bridge_live.py basindaki SkipTest). Onlari acikca + # kosturan is ayri dosyada: `istege-bagli-testler.yml`. + working-directory: service + run: python -m unittest discover -s tests -t . -v + + # ========================================================================= + sozlesme: + name: "Katman 3 -- sozlesme (model<->fiyat, yol<->izin listesi)" + if: github.event_name == 'push' + concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }}-sozlesme + cancel-in-progress: true + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: "Sozlesme denetimi" + # BU DENETIM BU PROJEDE IKI KEZ SESSIZ KUSUR YAKALARDI: + # + # 1. Model adi uyusmazligi. `cost_usd()` bilinmeyen bir model adi + # gorunce hata vermez, sessizce EN PAHALI tarifeye duser + # (provider.py:124-125). Butce raporu yanlis cikar, hicbir test + # kirilmaz. + # + # 2. Izin listesi sapmasi. `protocol.py:AI_API_ALLOWLIST`, + # backend'in `constant.rs:656-676` listesinin ELLE tutulan + # kopyasidir. Ayristiklarinda cagri `path_not_allowed` ile tele + # cikmadan reddedilir; testler de ayni kopyayi dogruladigi icin + # yesil kalir. + # + # NOT: GitHub kosucusunda backend deposu YOKTUR, bu yuzden gercek + # `constant.rs` karsilastirmasi burada ATLANIR ve betik bunu bir + # "not" olarak basar (hata degil). Depo ici pinli anlik goruntuye + # (tests/test_protocol.py:BACKEND_SNAPSHOT) karsi denetim yine kosar. + # Gercek karsilastirma yerelde yapilir: + # HEZARFEN_BACKEND=/yol/hezarfen_backend-main python scripts/ci-sozlesme.py + run: python scripts/ci-sozlesme.py + + # ========================================================================= + sirlar: + name: "Katman 4 -- sir taramasi (sizmis API anahtari)" + if: github.event_name == 'push' + concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }}-sirlar + cancel-in-progress: true + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + - name: "Sir taramasi" + # `.env` `.gitignore` icinde, ama bu yalnizca YENI dosyalari korur: + # `git add -f` ile ya da `.gitignore`'dan once eklenmis bir dosya + # izlenmeye devam eder. Tarayici `sk-` / `sk_` desenlerini, ozel + # anahtar govdelerini ve yapilandirma dosyalarina gomulmus duz + # degerleri arar; ayrica compose'daki zorunlu sirlarin `${VAR:?}` + # bicimini korudugunu dogrular. + # + # Bulunan deger ASLA tam basilmaz -- yoksa CI kaydinin kendisi sir + # sizdiran yer olurdu. + run: python scripts/ci-sir-tara.py + + # ========================================================================= + konteyner: + name: "Katman 5 -- konteyner (derleniyor VE kosuyor mu)" + if: github.event_name == 'push' + concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }}-konteyner + cancel-in-progress: true + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: "Imaji derle" + # Taban imaj digest'e pinlidir (Containerfile:15); bu is ayni zamanda + # o digest'in hala cekilebildigini de dogrular. + working-directory: service + run: podman build -t hezarfen-zeka:ci -f Containerfile . + + - name: "Imaj boyutu" + run: podman images --format '{{.Repository}}:{{.Tag}} {{.Size}}' hezarfen-zeka:ci + + - name: "Kosu kaniti -- kap cikmiyor, non-root, saglik kontrolu olcuyor" + # DERLENDI, KOSTU DEMEK DEGILDIR. Denetimde kardes servis RAG'in + # konteynerinin hic ayaga kalkmadigi bulundu: komut bir metin basip + # cikiyor ve `restart: unless-stopped` ile sonsuz crash-loop + # uretiyordu. Bu adim farki olcer: + # - kap 50 sn sonra hala kosuyor mu, + # - backend YOKKEN cikmak yerine USTEL geri cekilmeyle yeniden + # deniyor mu (bekleme suresi buyuyor mu), + # - surec non-root mu (uid 10002), + # - saglik kontrolu kopru yasarken geciyor VE kopru yokken + # kaliyor mu (her zaman 0 donen bir kontrol hicbir sey kanitlamaz). + run: bash scripts/ci-konteyner-kanit.sh podman hezarfen-zeka:ci + + - name: "compose.yaml gecerli mi ve zorunlu sirlar zorunlu mu" + # Iki yonlu denetim: (1) zorunlu env YOKKEN `config` PATLAMALI, + # (2) VARKEN gecerli bir yapilandirma uretmeli. Yalnizca ikincisini + # denetlemek, `${VAR:?}` yerine `${VAR:-}` yazilmasini yakalamaz. + # + # ZORUNLU SIRLAR LISTESI compose.yaml'IN KENDISINDEN OKUNUR: ucuncu + # sir `ZEKA_PG_DSN` (compose.yaml:82) eklendiginde bu adim ve yerel + # esdegeri `scripts/ci-compose.sh` iki sirla kalmis, adim "sirlar + # verilse bile patliyor" diyerek KIRMIZI kalmisti. Liste artik tamdir; + # compose.yaml'a sir eklerken burayi da guncelleyin (ve + # scripts/ci-compose.sh'i; yerel esdeger AYNI kapi olmali). + working-directory: service + run: | + echo "--- zorunlu env eksikken patlamali ---" + if env -u AI_SHARED_TOKEN -u DEEPSEEK_API_KEY -u ZEKA_PG_DSN \ + docker compose config >/dev/null 2>&1; then + echo "HATA: zorunlu sirlar olmadan gecti;" + echo " zorunlu sirlar \${VAR:?} bicimini kaybetmis olabilir." + exit 1 + fi + echo "ok: zorunlu env olmadan reddedildi" + echo "--- zorunlu env varken gecerli olmali ---" + AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte \ + ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci docker compose config + echo "--- port ACILMAMALI (disa arama servisi) ---" + if AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte \ + ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci docker compose config \ + | grep -qE '^\s+ports:'; then + echo "HATA: compose port aciyor; ZEKA backend'e dial-out eder, port ACMAZ." + exit 1 + fi + echo "ok: hicbir port yayimlanmiyor" + + # ========================================================================= + build: + name: Build and test + # Push'ta kosar. Dispatch, suiti tekrar odemek yerine en yeni yesil + # artefakti kullanir (bkz. deploy'un "Find the newest green build" adimi). + if: github.event_name == 'push' + # BES KATMANIN HEPSI yesil olmadan artefakt uretilmez: bozuk bir build + # sunucuya ASLA ulasmamali. Suiti burada TEKRAR kosmuyoruz -- `needs:` + # zinciri Katman 2'yi zaten sart kostu; bu isin ekledigi sey, ayni agactan + # uretilen SURUM paketidir. + needs: [sozdizimi, testler, sozlesme, sirlar, konteyner] + concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }}-build + cancel-in-progress: true + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Build the image + # Laptop ve CI ayni Containerfile'i kullanir: ayri bir CI ikizi yok. + # Baglam `service/` -- Containerfile oradadir. + working-directory: service + run: | + set -euo pipefail + podman build -t localhost/hezarfen-zeka:$GITHUB_SHA -f Containerfile . + + - name: Stage the release bundle + # Sunucuda kurulacak her sey burada olmali; eksik parca burada, + # sunucuda degil, patlar. + run: | + set -euo pipefail + mkdir -p stage + podman save localhost/hezarfen-zeka:$GITHUB_SHA | gzip > stage/hezarfen_zeka.tar.gz + cp service/compose.yaml stage/compose.yaml + cp deploy/hezarfen_zeka_compose.service stage/ + echo -n "$GITHUB_SHA" > stage/tag + test -f stage/hezarfen_zeka.tar.gz + test -f stage/compose.yaml + test -f stage/hezarfen_zeka_compose.service + test -f stage/tag + ls -lh stage + + # Deploy isi (ve elle yeniden deploy) bunu tuketir. 30 gun, dispatch + # kapisinin geri uzanma penceresidir. + - name: Upload the release + uses: actions/upload-artifact@v4 + with: + name: release + path: stage + retention-days: 30 + + # ========================================================================= + deploy: + name: Deploy + # Zincirin tamami kapi olur: build'in `needs` listesi bes katmani kapsar, + # yani `needs: [build]` "bes katman + imaj yesil" demektir. + needs: [build] + concurrency: + group: deploy + cancel-in-progress: false + # Push: yalniz Build and test yesilse. Dispatch: iki CI isi bilerek + # atlanir (if'lerine bakin) ve `always()` bu atlamanin bu kapidan + # gecmesini saglar. + if: >- + always() && + ((github.event_name == 'push' && needs.build.result == 'success') || + (github.event_name == 'workflow_dispatch' && needs.build.result == 'skipped')) + runs-on: ubuntu-24.04 + steps: + # Push deploy'u bu kosunun urettigi ve kapiladigi surumu alir. + - name: Fetch this run's release + if: github.event_name == 'push' + uses: actions/download-artifact@v4 + with: + name: release + path: stage + + # Elle yeniden deploy, BUILD isi yesil olan en yeni kosuyu alir -- en + # yeni tamamen yesil kosuyu degil: bir kosu saglik kapisinda dusmus + # olabilir ama build'i tam da geri almak istedigimiz surumdur. + - name: Find the newest green build + if: github.event_name == 'workflow_dispatch' + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + run_id="" + for rid in $(gh run list --workflow main.yml --branch main --event push --limit 15 --json databaseId --jq '.[].databaseId'); do + if [ "$(gh run view "$rid" --json jobs --jq '.jobs[] | select(.name=="Build and test") | .conclusion')" = "success" ]; then + run_id=$rid + break + fi + done + if [ -z "$run_id" ]; then + echo 'no run on main has a green Build-and-test job (or its artifact has expired)' >&2 + exit 1 + fi + echo "redeploying the release from run $run_id" + echo "run_id=$run_id" >> "$GITHUB_ENV" + + - name: Fetch the green release + if: github.event_name == 'workflow_dispatch' + uses: actions/download-artifact@v4 + with: + name: release + path: stage + run-id: ${{ env.run_id }} + github-token: ${{ github.token }} + + # Dispatch yolu gunler oncesine ait bir artefakt indirebilir; sunucuya + # dokunmadan once paketin butun oldugunu yeniden kontrol et. + - name: Check the release is complete + run: | + set -euo pipefail + test -f stage/hezarfen_zeka.tar.gz + test -f stage/compose.yaml + test -f stage/hezarfen_zeka_compose.service + test -f stage/tag + + - name: Install SSH keys + run: | + mkdir -p ~/.ssh + echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa + ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts + + - name: Upload the release + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + + # Sunucunun login shell'i bash degil, ssh bu betigi ona verirdi; + # `bash -s` betigi stdin'den alir, login shell yalniz tek duz komut + # gorur. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE' + set -euo pipefail + case "$1" in + ''|/*|*..*) + echo "Refusing a broad deploy subdirectory: '$1'" >&2 + exit 1 + ;; + esac + deploy_path=$HOME/$1 + # Bu dizin operatorun hezarfen_zeka.env dosyasini, compose + # dosyalarini ve tag dosyalarini tutar; hicbiri toptan silinmez. + mkdir -p -- "$deploy_path" + REMOTE + # stdin paketi tasiyor, betik tasiyamaz; cikarma yine bash -c ile + # cunku login shell bash degil ve $HOME'u genisletmez. Sunucuya + # yalnizca dort deploy dosyasi kurulur. + tar -C stage -czf - hezarfen_zeka.tar.gz compose.yaml hezarfen_zeka_compose.service tag | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1\"' -- '$DEPLOY_SUBDIR'" + + - name: Load the image and restart the bridge + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + + # bash -s, yukaridakiyle ayni sebeple: login shell bu betigi asla + # gormemeli. + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME' '$CONTAINER_NAME' '$CERT_PATH' '$BACKEND_HTTP_PORT'" <<'REMOTE' + set -euo pipefail + deploy_path=$HOME/$1 + service=$2 + env_file=$deploy_path/$3 + container=$4 + cert_path=$5 + backend_http_port=$6 + export XDG_RUNTIME_DIR=/run/user/$(id -u) + # compose.yaml calisma dizininden cozulur: unit'in ExecStart'i + # WorkingDirectory tasir ama rollback'in compose up'i ve ilk + # deploy'un down'i tam buradan kosar. + cd -- "$deploy_path" + + # Hicbir sey oynamadan once oku: ayar dosyasi operatorun, sunucuda, + # elle bir kez yazilir (anahtarlar icin bkz. + # deploy/hezarfen_zeka.env.example). Deploy onu ASLA olusturmaz, + # ezmez. + if [ ! -f "$env_file" ]; then + echo "missing $env_file -- create it (0600) from deploy/hezarfen_zeka.env.example" >&2 + exit 1 + fi + chmod 0600 -- "$env_file" + + # KAPASITE ON KONTROLU -- aile deseni (RAG'in ayni adimi 12 GB / 20 GB + # esikleri kullaniyor; orada ~4,5 GB model + birkac GB RSS var ve + # GPU'suz makinede urun kapisi gecmiyor). ZEKA hafiftir: olculen imaj + # 152 MB (docs/DAGITIM.md), calisma zamani tek bir Python sureci, + # model yok. Esikler bu yuzden olculenin ~10 katidir: pay birakip + # gereksiz reddetmemek icin. Yetersizse OOM ile canli stack'i + # dusurmek yerine burada, NEDENIYLE reddedilir. + avail_mb=$(awk '/MemAvailable/ {print int($2/1024)}' /proc/meminfo) + disk_gb=$(df -BG --output=avail "$deploy_path" | tail -1 | tr -dc '0-9') + if [ "$avail_mb" -lt 512 ] || [ "$disk_gb" -lt 2 ]; then + echo "refusing to deploy: ${avail_mb} MB RAM available (need >= 512) and ${disk_gb} GB disk (need >= 2)." >&2 + echo 'ZEKA is light (152 MB image, one Python process, no models) but a host without headroom will not get it; free space or deploy elsewhere.' >&2 + exit 1 + fi + + # Rootless podman + compose saglayici; uc adim sonra ciplak + # command-not-found yerine cozumu soyle. + command -v podman >/dev/null || { + echo "podman not found -- install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2 + exit 1 + } + podman compose version >/dev/null 2>&1 || { + echo "'podman compose' unavailable -- install a compose provider (podman-compose or docker-compose)" >&2 + exit 1 + } + + # ON KOSUL, KAPI DEGIL: backend'in kopru dinleyicisi acik mi + # (AI_QUIC_ADDR=0.0.0.0:8090) -- sertifika ucu bunun kanitidir. + # Celebi bunu KAPI yapar; ZEKA'da bilerek UYARIDIR, cunku kopru + # backend yokken CIKMAZ: ustel geri cekilmeyle bekler ve backend + # duzeltilince kendiliginden kaydolur + # (src/bridge.py::run_forever, docs/DAGITIM.md "Servis ne yapar"). + # Backend bakimda diye ZEKA'nin dagitimini reddetmek, servisin kendi + # sozlesmesinden DAHA SIKI bir sart koymak olurdu -- yani urunun + # tanimadigi bir "kayit" kapisi. + served_cert=$(curl -fsS "http://127.0.0.1:${backend_http_port}${cert_path}" 2>/dev/null) || true + case "$served_cert" in + *certificate_pem*) echo "ok: backend sertifikayi sunuyor (kopru kayit olabilir)" ;; + *) + echo "UYARI: backend ${cert_path} sertifika dondurmedi -- AI koprusu kapali olabilir (hezarfen_backend.env icinde AI_QUIC_ADDR=0.0.0.0:8090). Kopru baglanana kadar bekleyecek; bu TASARIM GEREGI bir bekleme halidir, ariza degil." >&2 + ;; + esac + + # BU build'in imajini yukle ve build'in damgaladigi tag'i oku + # (build zamani ile deploy zamani neyin gittiginde anlasmali). + gunzip -c "$deploy_path/hezarfen_zeka.tar.gz" | podman load + tag=$(cat -- "$deploy_path/tag") + + # Tag rotasyonu: previous_tag geri donus hedefidir (ilk deploy'da + # yok); current_tag su an calismasi gerekeni kaydeder. + if [ -f "$deploy_path/current_tag" ]; then + cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag" + fi + printf '%s\n' "$tag" > "$deploy_path/current_tag" + + # stack.env deploy sahipli (operatorun ayar dosyasindan farkli): + # yalniz imaj tag'ini tasir ve --env-file sirasi HEZARFEN_TAG'de onu + # kazanan yapar (compose.yaml: `localhost/hezarfen-zeka:${HEZARFEN_TAG:-current}`). + printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env" + + chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen_zeka_compose.service" + # Imaj tarball'i yalniz tasiyiciydi; imaj artik podman deposunda. + rm -f -- "$deploy_path/hezarfen_zeka.tar.gz" + + compose_up() { + podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" up -d --no-build + } + rollback() { + if [ -f "$deploy_path/previous_tag" ]; then + prev=$(cat -- "$deploy_path/previous_tag") + printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env" + printf '%s\n' "$prev" > "$deploy_path/current_tag" + compose_up + echo "rolled back to $prev" >&2 + else + # Ilk deploy: geri donulecek bir sey yok, yari ayakta stack'i + # durdur. Duz down -- `-v` YOK: zeka-fixtures isimli volume + # stop'ta yasamali. + podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" down + echo 'first deploy failed; stack stopped, volumes kept' >&2 + fi + } + + # Unit surumuyle birlikte gelir: yeni kurulmus bir kutuda ilk + # deploy'a kadar unit yoktur ve degisen unit onu gerektiren compose + # ile iner. + mkdir -p -- "$HOME/.config/systemd/user" + install -m 0644 -- "$deploy_path/hezarfen_zeka_compose.service" "$HOME/.config/systemd/user/$service.service" + systemctl --user daemon-reload + + # Unit RemainAfterExit'li bir oneshot: aktif (exited) unit'te `start` + # no-op olurdu -- her deploy ExecStart'i yeniden kosmak icin restart + # eder. Dusen bir restart (kotu interpolasyon, saglayici aksakligi) + # yine de asagidaki saglik kapisina ulasmali: karari o verir. + systemctl --user enable -- "$service" + systemctl --user restart "$service" || true + + # SAGLIK KAPISI -- SERVISIN KENDI betigi. `scripts/saglik.py` + # konteynerde her 30 saniyede kosan kontrolun TA KENDISIDIR; portu + # olmayan bir serviste disaridan yoklanacak bir ucu yoktur. + # + # NE ARAR: kopru surecinin YASADIGINI (zombi degil). NE ARAMAZ: + # backend'e KAYITLI oldugunu -- bu KASITLIDIR ve compose.yaml'daki + # `healthcheck` blogunun gerekcesidir: hazir olma sarti aransaydi + # backend'in her yeniden dagitimi ZEKA'yi `unhealthy` isaretler ve + # restart politikasi kacinmaya calistigimiz crash-loop'u geri + # getirirdi. Deploy da bir kayit kapisi UYDURMAZ; uyduracagi kapi + # servisin kendi tanimindan daha siki olurdu. + # + # 60 deneme: yorumlayici + aioquic import'u ve kap acilisi icin + # comert. + ready_ok=0 + for _ in $(seq 1 60); do + if podman exec "$container" python scripts/saglik.py >/dev/null 2>&1; then + ready_ok=1 + break + fi + sleep 1 + done + if [ "$ready_ok" -ne 1 ]; then + echo "the health script never passed ('src.bridge' process is not alive); rolling back" >&2 + podman logs --tail 30 "$container" >&2 || true + rollback + exit 1 + fi + + # Eski bir stack de saglikli olabilir; calisan konteyner BU build'in + # imaji olmali, yoksa geri donulur. + image=$(podman inspect -f '{{.Config.Image}}' "$container") + case "$image" in + *"$tag"*) ;; + *) + echo "the health gate passed, but the container runs '$image' -- not this build ($tag); rolling back" >&2 + rollback + exit 1 + ;; + esac + echo 'hezarfen_zeka_compose is up' + REMOTE + + # Bagimsiz son kontrol: cevap veren konteyner hala guncel tag'in olmali + # ve kopru yasiyor olmali -- servisin KENDI saglik betigiyle, yeniden. + - name: Verify the bridge is alive + run: | + set -euo pipefail + ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" + ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$CONTAINER_NAME'" <<'REMOTE' + set -euo pipefail + deploy_path=$HOME/$1 + container=$2 + export XDG_RUNTIME_DIR=/run/user/$(id -u) + cd -- "$deploy_path" + tag=$(cat -- "$deploy_path/current_tag") + image=$(podman inspect -f '{{.Config.Image}}' "$container") + case "$image" in + *"$tag"*) ;; + *) + echo "container runs '$image', not the current tag '$tag'" >&2 + exit 1 + ;; + esac + status=$(podman inspect -f '{{.State.Status}}' "$container") + [ "$status" = "running" ] || { echo "container status is '$status', not running" >&2; exit 1; } + podman exec "$container" python scripts/saglik.py || { + echo "the bridge process is not alive (scripts/saglik.py failed)" >&2 + exit 1 + } + echo 'bridge alive, container is this build' + REMOTE + + - name: Cleaning + run: rm -rf ~/.ssh diff --git a/Makefile b/Makefile index f087a7f..7a1b735 100644 --- a/Makefile +++ b/Makefile @@ -61,7 +61,7 @@ compose: ## compose.yaml gecerli mi; zorunlu sirlar zorunlu mu; port acik mi # --- gunluk kullanim ------------------------------------------------------- -kos: ## Servisi compose ile kaldir (zorunlu: AI_SHARED_TOKEN, DEEPSEEK_API_KEY) +kos: ## Servisi compose ile kaldir (zorunlu: AI_SHARED_TOKEN, ZEKA_PG_DSN, DEEPSEEK_API_KEY) cd service && $(MOTOR) compose up -d loglar: ## Servis gunluklerini izle diff --git a/README.md b/README.md index 8378b0d..6ee5329 100644 --- a/README.md +++ b/README.md @@ -297,3 +297,64 @@ günler sonra boş bir tablo yerine. DSN hiçbir yerde loglanmaz; `pg_client._describe()` yalnız host/port/veritabanı döndürür, kullanıcı adı ve parola asla. + +--- + +## 11. Dağıtım — VPS, yeşil push'ta otomatik + +`.github/workflows/main.yml` — ailedeki Çelebi deploy'uyla **aynı şekil**: + +``` +Katman 1..5 (paralel) -> Build and test -> Deploy (SSH, health gate, tag rollback) +``` + +| İş | Ne yapar | +|---|---| +| **Katman 1..5** | `ci.yml`'deki beş katmanın kendisi; komutlar birebir aynı. Hepsi yeşil olmadan imaj üretilmez. | +| **Build and test** | İmajı bu koşunun SHA'sıyla derler (`localhost/hezarfen-zeka:$GITHUB_SHA`), imaj tarball'ı + `compose.yaml` + systemd unit'i + `tag` dosyasını `release` artefaktı olarak yükler (30 gün). | +| **Deploy** | SSH: kapasite ön kontrolü → imajı yükle → `stack.env`'in `HEZARFEN_TAG`'ini bu SHA'ya çevir → compose + unit'i kur → `systemctl --user restart` → **servisin kendi sağlık betiğiyle** doğrula → olmazsa önceki tag'e dön → bağımsız son doğrulama. | + +**Yeşil bir `main` push'u servisi otomatik dağıtır.** Elle yeniden dağıtım +(süiti tekrar koşmadan, en yeni yeşil build'i): + +```bash +gh workflow run main.yml --ref main +``` + +`main` dalına push yalnızca `main.yml`'de koşar; **diğer dallar ve pull +request'ler** beş katmanı `ci.yml`'den alır (aynı kapı iki kez koşmaz). + +### Ön koşullar (bir kez, depo/sunucu dışında yapılır) + +1. **Repo secret'ları** — backend ve frontend deploy'unun kullandığı üç isim: + `SSH_PRIVATE_KEY`, `SSH_HOST`, `SSH_USER`. +2. **Sunucuda `loginctl enable-linger `** — kullanıcı unit'i için. +3. **Sunucuda podman + bir compose sağlayıcı** (`podman compose version`). +4. **Operatörün ayar dosyası** — deploy onu **oluşturmaz, yazmaz**, yalnız + varlığını kontrol eder ve izni 0600'e çeker: + + ```bash + mkdir -p ~/hezarfen_zeka + cp deploy/hezarfen_zeka.env.example ~/hezarfen_zeka/hezarfen_zeka.env + # AI_SHARED_TOKEN / ZEKA_PG_DSN / DEEPSEEK_API_KEY zorunlu + chmod 0600 ~/hezarfen_zeka/hezarfen_zeka.env + ``` + +5. **Backend tarafı açık olmalı**: `hezarfen_backend.env` içinde + `AI_QUIC_ADDR=0.0.0.0:8090` ve `AI_SHARED_TOKEN` bu köprününkiyle **aynı**. + Bu bir **kapı değildir**: ZEKA backend yokken çıkmaz, bekler ve backend + düzeltilince kendiliğinden kaydolur (bkz. `docs/DAGITIM.md`). Deploy bunu + yalnız **uyarı** olarak bildirir — kayıt şartı aransaydı ZEKA'nın kendi + tanımından daha sıkı bir kapı uydurmuş olurduk. + +### Kapı, rollback ve kapsam + +- **Sağlık kapısı = `scripts/saglik.py`**, konteynerde. Ölçtüğü şey köprü + sürecinin **yaşaması**; backend'e *kayıtlı* olduğunu ölçmez — bu bilinçli + (backend'in her yeniden dağıtımı ZEKA'yı `unhealthy` işaretlemesin diye). +- **Kapasite ön kontrolü**: ≥ 512 MB boşta RAM ve ≥ 2 GB disk; yetmezse + **nedeniyle birlikte reddeder** (ölçülen: imaj 152 MB, model yok). +- **Rollback**: `previous_tag`'e döner; ilk dağıtımda geri dönülecek imaj + yoksa stack durdurulur (`down`, `-v` **yok** — `zeka-fixtures` volume'u kalır). +- **Manuel yol duruyor**: `cd service && podman compose up -d` (bkz. §7) — + deploy'a ihtiyaç duymadan tek makinede kaldırmak için değişen bir şey yok. diff --git a/deploy/hezarfen_zeka.env.example b/deploy/hezarfen_zeka.env.example new file mode 100644 index 0000000..499a09a --- /dev/null +++ b/deploy/hezarfen_zeka.env.example @@ -0,0 +1,115 @@ +# hezarfen_zeka.env -- ZEKA koprusunun SUNUCU ayarlari. +# +# Sunucuda TEK SEFERLIK, elle: +# mkdir -p ~/hezarfen_zeka +# cp deploy/hezarfen_zeka.env.example ~/hezarfen_zeka/hezarfen_zeka.env +# +# chmod 0600 ~/hezarfen_zeka/hezarfen_zeka.env +# +# Hicbir otomasyon bu dosyayi OLUSTURMAZ, EZMEZ, YUKLEMEZ -- operatorun malidir; +# deploy yalnizca varligini kontrol eder ve iznini 0600'e ceker, compose yalniz +# okur (`--env-file`). Satirlar duz KEY=value: tirnak yok, `export` yok, satir +# sonu yorumu yok. Yerel gelistirme icin esdegeri `service/.env.example`'dir. +# +# Degerler konteyner BASLARKEN okunur: degisiklikten sonra yeniden olustur +# podman compose --env-file hezarfen_zeka.env --env-file stack.env up -d +# ya da +# systemctl --user restart hezarfen_zeka_compose +# +# Uc sir ZORUNLUDUR (`${VAR:?}`): bos birakilirsa `compose up` DAHA BASLAMADAN +# durur -- adressiz/anahtarsiz bir kopru ayaga kalkip hicbir sey yazmadan +# "calisiyor" gorunurdu ve hata gunler sonra bos bir tablo olarak cikardi. + +# ============================================================================ +# ZORUNLU +# ============================================================================ + +# Backend ile AYNI sir. Kopru kaydi bununla yapilir; hezarfen_backend.env +# icindeki AI_SHARED_TOKEN ile BIREBIR ayni olmali (iki tarafi birlikte +# degistirin; yalniz birini degistirmek kaydi `unauthorized` ile dusurur ve +# kopru bekler). +AI_SHARED_TOKEN= + +# ZEKA ciktilarini yazacagi veritabani. OKULUN kendi veritabanidir; ayri bir +# ZEKA veritabani YOKTUR. Adi okulun uuid'sinden turer (`tenant.rs:112`), slug'dan +# DEGIL: +# hezarfen_control_school_0193000000007000800000000000de70 +# Parola tasir: dosya 0600, DSN hicbir yere loglanmaz. +ZEKA_PG_DSN= + +# Segment hattinin LLM saglayicisi. Kopru bu anahtari OKUMAZ; yalnizca +# `src/segment/` okur (oncelik: DEEPSEEK_API_KEY -> LLM_API_KEY -> +# SEGMENT_API_KEY). Yine de zorunlu tutuluyor: anahtarsiz bir servis ayaga +# kalkar, segment hatti kosuldugunda patlardi. Hatayi dagitim anina cekiyoruz. +# (Yalnizca kopruyu kosturan bir dagitimda bilincli olarak sahte bir deger +# verilebilir; segment o zaman hata verir, kopru calisir.) +DEEPSEEK_API_KEY= + +# ============================================================================ +# KOPRU +# ============================================================================ + +# Backend'in QUIC dinleyicisi (konteyner aginda). Backend tarafinda +# AI_QUIC_ADDR=0.0.0.0:8090 OLMALI -- 127.0.0.1 yaziliysa backend yalniz kendi +# konteyner loopback'ine baglanir ve HICBIR servis dial-in edemez. +AI_BRIDGE_HOST=hezarfen-backend +AI_BRIDGE_PORT=8090 + +# Sertifikanin cekildigi HTTP koku. Varsayilan backend konteynerinin kendi +# adresi; backend'in yayimlanan host portu ise 127.0.0.1:7656'dir. +AI_BACKEND_URL=http://hezarfen-backend:8080 +AI_TLS_SERVER_NAME=localhost +AI_SERVICE_NAME=zeka + +# Sertifika parmak izi pinlemesi -- BACKEND SERTIFIKASI DUZ HTTP ILE CEKILDIGI +# icin tek basina pinlemek yetmez: araya giren biri kendi sertifikasini +# pinletebilir. BOS BIRAKILIRSA TOFU (her acilista uyari olarak loglanir; +# sessiz bir varsayilan degildir). Uretimde doldurun -- 64 hex karakter, iki +# nokta ayraclari atilir. Sunucuda: +# curl -s http://127.0.0.1:7656/ai/certificate | python -c 'import json,sys; print(json.load(sys.stdin)["fingerprint_sha256"])' +AI_TLS_FINGERPRINT= + +AI_MAX_CONCURRENT=4 +AI_RECONNECT_SECS=3 +AI_RECONNECT_MAX_SECS=120 + +# ============================================================================ +# KAPSAM +# ============================================================================ +# +# Backend'de okul ve kullanici LISTELEME yolu yok (izin listesi +# `constant.rs:641-661`), bu yuzden kapsam BURADAN verilir -- donem ortasi +# kayit olan ogrenci gorunmez, ayrilan silinmez. +# Bkz. service/docs/BACKEND-GEREKSINIMLERI.md madde 3. +ZEKA_SCHOOLS=hezarfen-demo +ZEKA_STUDENT_SOURCE=config +ZEKA_STUDENTS= +ZEKA_STUDENT_FILE= + +# ============================================================================ +# ZAMANLAMA +# ============================================================================ +# 0 = periyodik kosu kapali, yalnizca istek uzerine. +ZEKA_REFRESH_INTERVAL_SECS=3600 +ZEKA_REFRESH_JITTER_SECS=60 +ZEKA_REFRESH_BATCH=25 + +# ============================================================================ +# AG / LOG +# ============================================================================ +# Backend'in compose agi. Dagitimdan dagitima degisebilir (parametrik). +HEZARFEN_NET=hezarfen_backend_default + +# debug | info | warn | error +LOG_LEVEL=info + +# ============================================================================ +# SURUM ETIKETI +# ============================================================================ +# BURADAN OKUNMAZ: HEZARFEN_TAG yalnizca compose interpolasyonudur ve deploy'un +# sahip oldugu stack.env icinde tasinir (ikinci `--env-file`, cakisan anahtarda +# o kazanir). Elle kostururken varsayilan `current`'tir; imaj sunucuda VAR +# olmali: +# podman compose up -d --build # burada derle +# podman load -i hezarfen_zeka.tar.gz +#HEZARFEN_TAG=current diff --git a/deploy/hezarfen_zeka_compose.service b/deploy/hezarfen_zeka_compose.service new file mode 100644 index 0000000..c75be3f --- /dev/null +++ b/deploy/hezarfen_zeka_compose.service @@ -0,0 +1,48 @@ +# systemd KULLANICI unit'i: ZEKA koprusunu podman compose ile calistirir. +# %h/hezarfen_zeka icinde beklenen dosyalar: +# compose.yaml bu repodan (deploy artefaktindan gelir) +# hezarfen_zeka.env 0600, deploy/hezarfen_zeka.env.example'dan +# ELLE yazilir -- otomasyon olusturmaz/ezmez +# stack.env deploy sahipli; HEZARFEN_TAG tasir +# +# Unit `--no-build` ile baslar, yani imaj sunucuda zaten olmali: +# podman compose build # burada derle +# podman load -i image.tar # ya da hazir imaji yukle (deploy bunu yapar) +# +# KAPASITE: ZEKA hafiftir -- olculen imaj 152 MB (docs/DAGITIM.md), model +# dosyasi yok, calisma zamani tek bir Python sureci (kopru). Dagitim yine de +# yer oldugunu olcer (main.yml "KAPASITE ON KONTROLU": >= 512 MB RAM, +# >= 2 GB disk) ve yetmezse nedeniyle birlikte reddeder. +# +# HEZARFEN_TAG compose.yaml'da `${HEZARFEN_TAG:-current}` olarak gecir; bu +# unit'te SONRAKI --env-file kazanir: once operatorun ayar dosyasi, sonra +# deploy sahipli stack.env. +# +# Dis ag (`hezarfen_backend_default`) backend compose'u tarafindan kurulur; +# yoksa once olusturun: podman network create hezarfen_backend_default +# +# Sadece ortam degiskeni degistiginde yeniden baslatma (ExecStart'i yeniden +# kosar, ortami degisen konteynerı yeniden olusturur): +# systemctl --user restart hezarfen_zeka_compose + +[Unit] +Description=Hezarfen ZEKA bridge (student analysis + recommendations over the school database) +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +RemainAfterExit=yes +WorkingDirectory=%h/hezarfen_zeka +# Sonraki --env-file cakisan anahtarda kazanir: once operatorun ayar dosyasi, +# sonra deploy sahipli stack.env (HEZARFEN_TAG). +ExecStart=/usr/bin/podman compose --env-file %h/hezarfen_zeka/hezarfen_zeka.env --env-file %h/hezarfen_zeka/stack.env up -d --no-build +# Env dosyalari BURADA DA verilir: compose her komutta dosyayi COZER ve ZEKA +# compose.yaml'inda uc sir `${VAR:?}` bicimindedir; env'siz bir `down` +# "required variable ... is missing a value" ile duser ve kap DURMAZ. +# `-v` yok: zeka-fixtures isimli volume stop'ta yasamali. +ExecStop=/usr/bin/podman compose --env-file %h/hezarfen_zeka/hezarfen_zeka.env --env-file %h/hezarfen_zeka/stack.env down +TimeoutStartSec=180 + +[Install] +WantedBy=default.target diff --git a/scripts/ci-compose.sh b/scripts/ci-compose.sh index 55f96e6..adfc11e 100644 --- a/scripts/ci-compose.sh +++ b/scripts/ci-compose.sh @@ -4,7 +4,8 @@ # Uc sey denetlenir ve UCU DE cift yonludur; yalnizca "gecerli mi" diye # sormak, asil kusurlari kacirir: # -# 1. Zorunlu sirlar gercekten zorunlu mu? +# 1. Zorunlu sirlar gercekten zorunlu mu? (AI_SHARED_TOKEN, DEEPSEEK_API_KEY, +# ZEKA_PG_DSN -- tam liste compose.yaml'da.) # `${VAR:?}` yerine `${VAR:-}` yazilirsa compose yine gecerli olur ama # servis bos bir token'la ayaga kalkar ve backend'e kaydolamaz. Bu # yuzden env YOKKEN `config`in PATLAMASINI da sinariz. @@ -38,14 +39,21 @@ gec() { echo " [ok] $1"; } kal() { echo " [HATA] $1"; HATA=1; } # --- 1a. zorunlu env EKSIKKEN patlamali ----------------------------------- -if env -u AI_SHARED_TOKEN -u DEEPSEEK_API_KEY "${COMPOSE[@]}" config >/dev/null 2>&1; then +# ZORUNLU SIRLAR LISTESI compose.yaml'DAN OKUNUR -- su an uctur +# (AI_SHARED_TOKEN, DEEPSEEK_API_KEY, ZEKA_PG_DSN). Ucuncusu eklendiginde bu +# betik ve `ci.yml`'in konteyner katmani iki sirla kalmis, ikisi de "sirlar +# verilse bile patliyor" diyerek KIRMIZI kalmisti. Sir eklerseniz bu listeyi +# ve ci.yml/main.yml adimini BIRLIKTE guncelleyin. +if env -u AI_SHARED_TOKEN -u DEEPSEEK_API_KEY -u ZEKA_PG_DSN \ + "${COMPOSE[@]}" config >/dev/null 2>&1; then kal "zorunlu sirlar olmadan gecti -- \${VAR:?} yerine \${VAR:-} yazilmis olabilir" else - gec "zorunlu sirlar olmadan REDDEDILDI (AI_SHARED_TOKEN / DEEPSEEK_API_KEY)" + gec "zorunlu sirlar olmadan REDDEDILDI (AI_SHARED_TOKEN / DEEPSEEK_API_KEY / ZEKA_PG_DSN)" fi # --- 1b. zorunlu env VARKEN gecerli olmali -------------------------------- -CIKTI="$(AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte "${COMPOSE[@]}" config 2>&1)" +ZORUNLU_ENV=(AI_SHARED_TOKEN=ci-sahte DEEPSEEK_API_KEY=ci-sahte ZEKA_PG_DSN=postgres://ci:ci@127.0.0.1:5432/ci) +CIKTI="$(env "${ZORUNLU_ENV[@]}" "${COMPOSE[@]}" config 2>&1)" if [ $? -ne 0 ]; then kal "zorunlu sirlar verildiginde bile config basarisiz:" echo "$CIKTI" | tail -10 @@ -63,8 +71,13 @@ fi # --- 3. ag adi parametrik mi ---------------------------------------------- if grep -q 'name: ${HEZARFEN_NET:-' compose.yaml; then gec "dis ag adi parametrik: \${HEZARFEN_NET:-hezarfen_backend_default}" - OZEL="$(HEZARFEN_NET=baska_ag AI_SHARED_TOKEN=x DEEPSEEK_API_KEY=x "${COMPOSE[@]}" config 2>/dev/null | grep -A2 '^networks:' | grep 'name:')" - if echo "$OZEL" | grep -q 'baska_ag'; then + # SIRA BAGIMSIZ arama: `networks:` blogunda anahtar sirasi saglayiciya gore + # degisir (podman-compose `external`i `name`den ONCE basar). Ilk surum + # `grep -A2 '^networks:'` ile pencere aciyordu ve ad satirini kacirip HATA + # veriyordu -- probe'un kendisi yanlisti, yapilandirma degil. + OZEL="$(env HEZARFEN_NET=baska_ag "${ZORUNLU_ENV[@]}" "${COMPOSE[@]}" config 2>/dev/null \ + | grep -E '^[[:space:]]+name:[[:space:]]*baska_ag[[:space:]]*$' | head -1)" + if [ -n "$OZEL" ]; then gec "HEZARFEN_NET gecersiz kilinabiliyor (test: baska_ag ->$OZEL)" else kal "HEZARFEN_NET gecersiz kilinamadi; parametre ise yaramiyor" diff --git a/scripts/ci-sir-tara.py b/scripts/ci-sir-tara.py index 3f8ddb4..c42a210 100644 --- a/scripts/ci-sir-tara.py +++ b/scripts/ci-sir-tara.py @@ -66,7 +66,8 @@ DESENLER: list[tuple[str, re.Pattern[str], str]] = [ r"""(?x) ^\s*(?:export\s+)? (DEEPSEEK_API_KEY|LLM_API_KEY|SEGMENT_API_KEY|AI_SHARED_TOKEN - |ZEKA_DB_PASSWORD|[A-Z0-9_]*(?:API_KEY|SECRET|PASSWORD|TOKEN)) + |ZEKA_DB_PASSWORD|ZEKA_PG_DSN + |[A-Z0-9_]*(?:API_KEY|SECRET|PASSWORD|TOKEN)) \s*[:=]\s* (?!\$) # ${VAR} interpolasyonu degil ["']?([^\s"'#]{12,})["']?\s*$ @@ -240,10 +241,14 @@ def main() -> int: # --- compose sirlarinin bicimi ------------------------------------------ # Zorunlu sirlar `${VAR:?...}` ile gelmeli; duz deger ya da `:-varsayilan` # bir sirri dosyaya gomer. + # + # LISTE compose.yaml'DAN OKUNUR: `ZEKA_PG_DSN` ucuncu sir olarak + # eklendiginde burasi ve `scripts/ci-compose.sh` iki sirla kalmisti. + # DSN bir parola tasir -- duz deger yazilabilseydi sir dosyaya girerdi. compose = KOK / "service" / "compose.yaml" if compose.exists(): icerik = io.open(compose, encoding="utf-8").read() - for degisken in ("AI_SHARED_TOKEN", "DEEPSEEK_API_KEY"): + for degisken in ("AI_SHARED_TOKEN", "DEEPSEEK_API_KEY", "ZEKA_PG_DSN"): satirlar = [s for s in icerik.splitlines() if s.strip().startswith(degisken + ":")] if not satirlar: uyarilar.append(f"compose.yaml icinde {degisken} tanimli degil") diff --git a/scripts/ci-yerel.sh b/scripts/ci-yerel.sh index 9ddd4d3..9218688 100644 --- a/scripts/ci-yerel.sh +++ b/scripts/ci-yerel.sh @@ -63,7 +63,13 @@ kosu "sozdizimi" "$PYTHON" -m compileall -q -x '(__pycache__|\.venv|venv)' \ katman "2/5 testler" \ "375+ birim testi; saf unittest, HICBIR bagimlilik gerektirmez" # `-t .` onemli: test kokunu servise sabitler, `src.` import'lari boylece cozulur. -kosu "birim testleri" bash -c "cd '$SERVIS' && '$PYTHON' -m unittest discover -s tests -t . -v 2>&1 | tail -20" +# +# `set -o pipefail` ICERIDE: `bash -c` yeni bir kabuk acar ve dis script'in +# `pipefail` secenegi oraya GECMEZ. Onsuz boru hattinin cikis durumu `tail`in +# durumudur -- yani 686 testten 3'u patlarken bile bu satir GECTI basardi +# (olculdu: `Ran 686 tests ... FAILED`, katman yine yesil). Yesil gorunen ama +# olcmeyen kapi, kapi degildir. +kosu "birim testleri" bash -c "set -o pipefail; cd '$SERVIS' && '$PYTHON' -m unittest discover -s tests -t . -v 2>&1 | tail -20" if [ "$HIZLI" -eq 1 ]; then echo "" diff --git a/service/compose.yaml b/service/compose.yaml index a36c852..4a417f6 100644 --- a/service/compose.yaml +++ b/service/compose.yaml @@ -7,7 +7,12 @@ services: build: context: . dockerfile: Containerfile - image: localhost/hezarfen-zeka:current + # HEZARFEN_TAG deploy tarafindan yazilan stack.env'den gelir (--env-file + # sirasi onu kazanan yapar). Yerelde/elle `up` icin varsayilan `current`: + # yani `podman compose up -d --build` yine calisiyor. Sabit bir `:current` + # yazilsaydi deploy yeni imaji yukleyip ESKI imaji kosmaya devam ederdi -- + # tag rotasyonu ve geri donus (previous_tag) bu satira baglidir. + image: localhost/hezarfen-zeka:${HEZARFEN_TAG:-current} container_name: hezarfen-zeka-bridge init: true command: ["python", "-m", "src.bridge"] diff --git a/service/docs/DAGITIM.md b/service/docs/DAGITIM.md index 2866554..db933b1 100644 --- a/service/docs/DAGITIM.md +++ b/service/docs/DAGITIM.md @@ -286,7 +286,11 @@ kullanildigi durum icin bir yedektir. Katmanli. Her katman ayri bir istir; bir katman kirmiziya dondugunde neyin bozuldugu is listesinden okunur. -### `.github/workflows/ci.yml` -- her degisiklikte +### `.github/workflows/ci.yml` -- pull request'ler ve `main` DIŞINDAKİ dallar + +`main`'e push burada **koşmaz**: aynı beş katman `main.yml` içinde koşar ve +deploy'u kapılar (bkz. bir sonraki başlık). Böylece push başına aynı kapı iki +kez koşmaz; PR'lar ve dal push'ları tam katmanlı süiti buradan alır. | Katman | Ne denetler | |---|---| @@ -296,6 +300,44 @@ bozuldugu is listesinden okunur. | **4 -- sir taramasi** | `sk-` / `sk_` desenleri, ozel anahtar govdeleri, AWS anahtarlari, yapilandirma dosyalarina gomulmus duz degerler; compose sirlarinin `${VAR:?}` bicimini korudugu. | | **5 -- konteyner** | Imaj derleniyor **ve kosuyor** mu; non-root mu; saglik kontrolu gercekten olcuyor mu; `compose config` gecerli mi ve port acilmiyor mu. | +### `.github/workflows/main.yml` -- `main` push'u, otomatik dağıtım + +Ailedeki Çelebi deploy'uyla aynı şekil; is grafiği: + +``` +Katman 1..5 (paralel) -> Build and test -> Deploy (SSH) +``` + +| İş | Tetik | Neyi kanıtlar / ne yapar | +|---|---|---| +| `sozdizimi`, `testler`, `sozlesme`, `sirlar`, `konteyner` | push (`main`) | `ci.yml`'deki beş katmanın **aynısı** (Komutlar birebir; tek doğruluk kaynağı `scripts/ci-yerel.sh`). Beşi de yeşil olmadan imaj üretilmez. | +| `build` (adı **Build and test**) | push, beş katmanı `needs` ile bekler | İmajı `localhost/hezarfen-zeka:$GITHUB_SHA` olarak derler; imaj tarball'ı (`podman save`), `service/compose.yaml`, `deploy/hezarfen_zeka_compose.service` ve `tag` dosyasını `release` artefaktı olarak yükler (30 gün). Eksik parça burada — sunucuda değil — patlar. | +| `deploy` | push'ta yalnız `Build and test` yeşilse; `workflow_dispatch`'te en yeni yeşil build'in artefaktıyla | SSH ile: kapasite ön kontrolü (≥ 512 MB RAM, ≥ 2 GB disk) → operatörün `~/hezarfen_zeka/hezarfen_zeka.env` dosyasını kontrol (0600'e çeker, **yazmaz**) → imajı `podman load` → tag rotasyonu (`current_tag`→`previous_tag`) → `stack.env`'e `HEZARFEN_TAG` → unit kurulumu + `daemon-reload` + `enable` + `restart` → **`scripts/saglik.py` ile sağlık kapısı** (60 sn) → konteynerin imajı bu tag mi → olmazsa önceki tag'e dön (ilk dağıtımda `down`, `-v` yok) → bağımsız son doğrulama → `rm -rf ~/.ssh`. | + +**Yeşil bir `main` push'u otomatik dağıtır.** Elle yeniden dağıtım (süiti tekrar +koşmadan): `gh workflow run main.yml --ref main`. + +Kapı hakkında dürüst not: **sağlık kapısı köprü sürecinin yaşadığını ölçer**, +backend'e *kayıtlı* olduğunu ölçmez — `scripts/saglik.py`'nin ta kendisi +kullanılır ve nedeni orada yazılıdır (kayıt şartı aransaydı backend'in her +yeniden dağıtımı ZEKA'yı `unhealthy` işaretler ve crash-loop üretirdi). Backend +sertifika ucu deploy'da yalnızca **uyarı** olarak kontrol edilir; Celebi'deki +gibi bir ön kapı değildir, çünkü ZEKA'nın backend yokken beklemesi tasarım +gereğidir. + +Bir seferlik ön koşullar: + +1. Repo secret'ları `SSH_PRIVATE_KEY` / `SSH_HOST` / `SSH_USER`. +2. Sunucuda `loginctl enable-linger `. +3. Sunucuda `podman` + bir compose sağlayıcı. +4. Operatörün `~/hezarfen_zeka/hezarfen_zeka.env` dosyası (0600; şablon + `deploy/hezarfen_zeka.env.example`, zorunlu üç sır: `AI_SHARED_TOKEN`, + `ZEKA_PG_DSN`, `DEEPSEEK_API_KEY`). +5. Sunucuda `hezarfen_backend_default` ağı (backend compose'u kurar) ve + backend tarafında `AI_QUIC_ADDR=0.0.0.0:8090`. + +Manuel yol değişmedi: `cd service && podman compose up -d` (§3). + ### `.github/workflows/istege-bagli-testler.yml` -- elle tetiklenir Her degisiklikte **kosmaz**. `aioquic` kurar ya da bir veritabani kaldirir; @@ -416,6 +458,23 @@ KATMAN 5/5 konteyner+compose -> GECTI BUTUN KATMANLAR GECTI ``` +> **Bu kayit 519 testlik hale aittir; durum o gunden beri degisti.** Bugun 686 +> test var ve **ucu temiz bir kopyada KIRMIZI** cunku depoda **olmayan** +> uretilmis tohum artefaktlarini istiyorlar (`work/` ve `seed/*.surql` +> `.gitignore`'da; tohum depoda degil, yalnizca ureticisi var): +> +> ``` +> ERROR tests.test_segment_pipeline.TestRealDataLoaders.test_items_enriched_yuklenir +> ERROR tests.test_segment_validate.TestGoldSet.test_gercek_veride_741_pozitif +> FAIL tests.test_segment_pipeline.TestRealDataLoaders.test_cevaplar_surql_dosyasindan_okunur +> ``` +> +> Yani Katman 2 GitHub kosucusunda da kirmizidir ve deploy fail-closed +> davranip **hic dagitmaz**. Tohumu uretmeden bu katman yesile donmez; iki yol +> var: (a) bu uc test de diger 120 ortam bagimli test gibi eksik artefaktta +> `SkipTest` ile atlar, (b) tohum artefaktlari kosuya verilir. Bu bir CI/deploy +> isi degil, test verisi isidir. + --- ## Kanitlanmayanlar @@ -453,40 +512,47 @@ Durustluk bolumu. Asagidakiler **kosturulmadi** ya da **dogrulanamadi**; ### Kanitlanmayan -- CI -7. **GitHub Actions is akislari GitHub'da hic kosmadi.** Depo bir git deposu - bile degil. YAML el ile yazildi; `actions/checkout@v4`, +7. **GitHub Actions is akislari GitHub'da hic kosmadi.** Depo artik bir git + deposu (origin: `Hezarfen-Co/hezarfen_zeka`), ama hicbir is akisi gercek bir + kosucuda **kosturulmadi**. YAML el ile yazildi; `actions/checkout@v4`, `actions/setup-python@v5` ve kosucudaki `podman` varliginin gercek bir kosucuda dogrulanmasi **yapilmadi**. Kosturulmus olan, ayni komutlari cagiran `scripts/ci-yerel.sh`'dir. -8. **`docker compose` yolu.** `ci.yml` icindeki compose adimi +8. **`main.yml` deploy zinciri hic kosturulmadi.** SSH, `podman load`, unit + kurulumu, saglik kapisi, tag rotasyonu ve rollback yollari **okundu ve yerel + olarak kismen dogrulandi** (compose interpolasyonu, kapasite aritmetigi, + sağlık betiginin konteynerde iki yonlu davranisi), ama gercek bir sunucuya + karsi **hic kosmadi**. Ilk gercek kosu bu maddeleri kapatacaktir. + +9. **`docker compose` yolu.** `ci.yml` icindeki compose adimi `docker compose` cagirir; yerelde `podman compose` zaten docker-compose'a devrettigi icin **ayni ikili** kosturuldu, ama GitHub kosucusundaki surumle **dogrulanmadi**. -9. **Makefile.** Bu makinede `make` **kurulu degil**; hicbir hedef +10. **Makefile.** Bu makinede `make` **kurulu degil**; hicbir hedef kosturulamadi. Hedefler `scripts/` betiklerini cagiran ince sarmalayicilar olsa da, Makefile'in kendisi **sinanmamistir**. Guvenilir yol dogrudan `bash scripts/ci-yerel.sh` kullanmaktir. -10. **`istege-bagli-testler.yml` isleri.** Ne `kopru-canli` ne `veritabani` +11. **`istege-bagli-testler.yml` isleri.** Ne `kopru-canli` ne `veritabani` isi kosturuldu. `tests/test_bridge_live.py` yerelde `aioquic` kurulu olmadigi icin **atlandi**; canli kopru testlerinin gectigi **gorulmedi**. -11. *(Bu madde kapatildi -- negatif sinama yapildi, bkz. asagisi.)* +12. *(Bu madde kapatildi -- negatif sinama yapildi, bkz. asagisi.)* ### Kanitlanmayan -- guvenlik -12. **Fiyat tablosunun dogrulugu.** `PRICING_VERIFIED = False`. Fiyatlar +13. **Fiyat tablosunun dogrulugu.** `PRICING_VERIFIED = False`. Fiyatlar `2026-08-28` tarihli ve saglayicinin dokumantasyonuna karsi elle **dogrulanmamistir**. Butce hesaplari bu tabloya dayanir. -13. **Sir taramasinin kapsami.** Tarayici `.gitignore` tarafindan korunan +14. **Sir taramasinin kapsami.** Tarayici `.gitignore` tarafindan korunan dosyalari **atlar** (ve `.env` ailesinin gercekten korundugunu ayrica - denetler). Depo bir git deposu olmadigi icin `git check-ignore` yerine + denetler). `git check-ignore` hala kullanilmaz; yerine `.gitignore` desenleri **elle** yorumlanir; karmasik desenlerde (negasyon `!`, dizin-koku `/` ayrimi) git ile birebir ayni davranmayabilir. -14. **Gecmis tarama yok.** Tarayici yalnizca **calisma agacini** okur. Git +15. **Gecmis tarama yok.** Tarayici yalnizca **calisma agacini** okur. Git gecmisine bir zamanlar islenmis bir anahtar bulunamaz.