From 8d904660b938b445c619d46862cc47ddf51214de Mon Sep 17 00:00:00 2001 From: Lars Stommer Date: Thu, 22 Oct 2026 15:28:00 +0200 Subject: [PATCH] Automatisches Deployment nach Strato (atomare Releases, Rollback, Gitea Actions) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - scripts/deploy.sh: Build aus Git-Stand (Composer ohne Dev, Vite), Upload per SSH, Migration, Caches, atomarer Umschalter current -> releases/, Gesundheitscheck mit automatischem Rollback; Befehle setup/deploy/rollback/releases/artisan; lokaler Testmodus - .gitea/workflows/deploy.yml: Tests bei jedem Push, Deployment bei Tags v* oder per Knopfdruck - Vorlagen scripts/deploy.example.env und .env.production.example (Strato MySQL, SMTP, IMAP) - Scheduler-Endpunkt /automation/scheduler als Ausweich für fehlende Cronjobs - ProductionSeeder für die Ersteinrichtung ohne Testdaten Co-Authored-By: Claude Opus 5.5 --- .env.production.example | 63 ++++++ .gitea/workflows/deploy.yml | 85 +++++++++ .gitignore | 4 + app/Http/Controllers/ChannelController.php | 14 ++ config/fewo.php | 6 + database/seeders/ProductionSeeder.php | 28 +++ routes/web.php | 1 + scripts/deploy.example.env | 23 +++ scripts/deploy.sh | 211 +++++++++++++++++++++ tests/Feature/SchedulerEndpointTest.php | 25 +++ 10 files changed, 460 insertions(+) create mode 100644 .env.production.example create mode 100644 .gitea/workflows/deploy.yml create mode 100644 database/seeders/ProductionSeeder.php create mode 100644 scripts/deploy.example.env create mode 100644 scripts/deploy.sh create mode 100644 tests/Feature/SchedulerEndpointTest.php diff --git a/.env.production.example b/.env.production.example new file mode 100644 index 0000000..a1537f4 --- /dev/null +++ b/.env.production.example @@ -0,0 +1,63 @@ +# Production settings – copy to /shared/.env on the server and fill in. +# Generate APP_KEY locally once: php artisan key:generate --show + +APP_NAME="Ferienwohnung Stommer" +APP_ENV=production +APP_KEY= +APP_DEBUG=false +APP_URL=https://www.fewo-stommer.de +APP_TIMEZONE=Europe/Berlin +APP_LOCALE=de +APP_FALLBACK_LOCALE=de +APP_FAKER_LOCALE=de_DE +APP_MAINTENANCE_DRIVER=file + +LOG_CHANNEL=daily +LOG_LEVEL=warning + +# Strato MySQL (Kundenlogin › Datenbanken und Webspace › Datenbanken verwalten) +DB_CONNECTION=mysql +DB_HOST= +DB_PORT=3306 +DB_DATABASE= +DB_USERNAME= +DB_PASSWORD= + +SESSION_DRIVER=database +SESSION_LIFETIME=120 +SESSION_SECURE_COOKIE=true +CACHE_STORE=database +QUEUE_CONNECTION=sync +FILESYSTEM_DISK=local + +# Strato mailbox fewo@stommer.de +MAIL_MAILER=smtp +MAIL_HOST=smtp.strato.de +MAIL_PORT=465 +MAIL_SCHEME=smtps +MAIL_USERNAME=fewo@stommer.de +MAIL_PASSWORD= +MAIL_FROM_ADDRESS="fewo@stommer.de" +MAIL_FROM_NAME="${APP_NAME}" + +FEWO_OWNER_NAME="Brigitte Stommer" +FEWO_OWNER_EMAIL=fewo@stommer.de +FEWO_NOTIFICATION_EMAIL=fewo@stommer.de +FEWO_BANK_ACCOUNT_HOLDER= +FEWO_BANK_IBAN= +FEWO_BANK_BIC= +FEWO_BANK_NAME= + +# Portal booking e-mails (fast path) +FEWO_MAILBOX_HOST=imap.strato.de +FEWO_MAILBOX_PORT=993 +FEWO_MAILBOX_ENCRYPTION=ssl +FEWO_MAILBOX_USERNAME=fewo@stommer.de +FEWO_MAILBOX_PASSWORD= +FEWO_MAILBOX_FOLDER=INBOX + +# Monitoring / automation (long random values, e.g. php -r "echo bin2hex(random_bytes(24));") +FEWO_HEALTH_TOKEN= +FEWO_SCHEDULER_TOKEN= +FEWO_AUTOMATION_SECRET= +FEWO_AUTOMATION_WEBHOOK_URL= diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..683de61 --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,85 @@ +# Tests on every push; deployment to Strato for tags "v*" or by hand (Gitea › Actions › Deploy › Run workflow). +# Needs a Gitea act_runner (e.g. on the private server) and these repository secrets: +# DEPLOY_SSH_KEY private key whose public key is stored at Strato (SFTP & SSH) +# DEPLOY_HOST ssh.strato.de +# DEPLOY_USER SSH user from the Strato customer login +# DEPLOY_PATH e.g. fewo-production +# DEPLOY_PHP e.g. /opt/RZphp84/bin/php-cli +# DEPLOY_URL e.g. https://www.fewo-stommer.de +name: Deploy + +on: + push: + branches: [main] + tags: ['v*'] + workflow_dispatch: + inputs: + environment: + description: Ziel + type: choice + options: [production, staging] + default: production + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.4' + extensions: mbstring, intl, gd, exif, zip, pdo_sqlite, sqlite3, fileinfo, openssl + tools: composer:v2 + + - uses: actions/setup-node@v4 + with: + node-version: '22' + cache: npm + + - name: Install + run: | + composer install --no-interaction --no-progress --prefer-dist + npm ci --no-audit --no-fund + npm run build + cp .env.example .env + php artisan key:generate + + - name: Tests + run: php artisan test --compact + + deploy: + needs: test + if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.4' + extensions: mbstring, intl, gd, exif, zip, fileinfo, openssl + tools: composer:v2 + + - uses: actions/setup-node@v4 + with: + node-version: '22' + cache: npm + + - name: SSH key + run: | + mkdir -p ~/.ssh + printf '%s\n' "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy_key + chmod 600 ~/.ssh/deploy_key + ssh-keyscan -H "${{ secrets.DEPLOY_HOST }}" >> ~/.ssh/known_hosts + + - name: Deploy + env: + DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }} + DEPLOY_USER: ${{ secrets.DEPLOY_USER }} + DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }} + DEPLOY_PHP: ${{ secrets.DEPLOY_PHP }} + DEPLOY_URL: ${{ secrets.DEPLOY_URL }} + run: | + export DEPLOY_SSH_KEY="$HOME/.ssh/deploy_key" + bash scripts/deploy.sh "${{ inputs.environment || 'production' }}" deploy diff --git a/.gitignore b/.gitignore index fad3ce2..c4f733f 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,7 @@ _ide_helper.php Homestead.json Homestead.yaml Thumbs.db + +# Deployment settings with access data +/scripts/deploy.*.env +!/scripts/deploy.example.env diff --git a/app/Http/Controllers/ChannelController.php b/app/Http/Controllers/ChannelController.php index 848f41e..abe204b 100644 --- a/app/Http/Controllers/ChannelController.php +++ b/app/Http/Controllers/ChannelController.php @@ -14,6 +14,7 @@ use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Http\Response; +use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Cache; /** @@ -63,6 +64,19 @@ public function health(Request $request): JsonResponse ], $ok ? 200 : 503); } + /** + * Runs the task scheduler once (fallback for hosting without suitable cron jobs). + */ + public function scheduler(Request $request): JsonResponse + { + $token = config('fewo.scheduler_token'); + abort_if(blank($token) || ! hash_equals($token, (string) $request->query('token')), 404); + + Artisan::call('schedule:run'); + + return response()->json(['ran_at' => now()->toIso8601String(), 'output' => trim(Artisan::output())]); + } + /** * Push variant of the e-mail fast path, e.g. from an n8n IMAP trigger: * JSON {message_id, from, subject, text, received_at}, signed like the automation webhook. diff --git a/config/fewo.php b/config/fewo.php index 1a7c318..fa20593 100644 --- a/config/fewo.php +++ b/config/fewo.php @@ -76,6 +76,12 @@ 'stale_after_minutes' => (int) env('FEWO_MAILBOX_STALE_AFTER_MINUTES', 15), ], + /* + | Fallback trigger for the task scheduler (e.g. from n8n every minute) if the hosting's cron jobs + | are not available or not frequent enough: GET /automation/scheduler?token=… . Empty = disabled. + */ + 'scheduler_token' => env('FEWO_SCHEDULER_TOKEN'), + /* | Optional external automation (e.g. a browser bot on a private server) that carries out | manual blocking tasks. Tasks are POSTed signed with HMAC-SHA256 of the body. diff --git a/database/seeders/ProductionSeeder.php b/database/seeders/ProductionSeeder.php new file mode 100644 index 0000000..84387f0 --- /dev/null +++ b/database/seeders/ProductionSeeder.php @@ -0,0 +1,28 @@ +exists()) { + $this->command?->warn('Es gibt bereits eine Website – Ersteinrichtung übersprungen.'); + + return; + } + + $this->call([PropertySeeder::class, WebsiteContentSeeder::class, SiteSeeder::class]); + } +} diff --git a/routes/web.php b/routes/web.php index 4d8326e..382ec17 100644 --- a/routes/web.php +++ b/routes/web.php @@ -15,6 +15,7 @@ Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1'); Route::get('/health/sync', [ChannelController::class, 'health'])->name('health.sync'); +Route::get('/automation/scheduler', [ChannelController::class, 'scheduler'])->name('automation.scheduler')->middleware('throttle:10,1'); Route::post('/automation/portal-mail', [ChannelController::class, 'portalMail']) ->name('channels.portal-mail') ->withoutMiddleware(PreventRequestForgery::class) diff --git a/scripts/deploy.example.env b/scripts/deploy.example.env new file mode 100644 index 0000000..92725e6 --- /dev/null +++ b/scripts/deploy.example.env @@ -0,0 +1,23 @@ +# Copy to scripts/deploy.production.env (or deploy.staging.env) and fill in. These files are not committed. + +# SSH access (Strato: Kundenlogin › Datenbanken und Webspace › SFTP & SSH) +DEPLOY_HOST=ssh.strato.de +DEPLOY_USER=www.fewo-stommer.de +DEPLOY_PORT=22 +# Optional: private key file (otherwise the SSH agent / default key is used) +# DEPLOY_SSH_KEY=~/.ssh/strato_fewo + +# Folder below the SSH start directory. The domain's target directory must be /current/public. +DEPLOY_PATH=fewo-production + +# PHP CLI on Strato shared hosting: /opt/RZphp/bin/php-cli (check with: ls /opt) +DEPLOY_PHP=/opt/RZphp84/bin/php-cli + +# Public address for the health check after switching (empty = no check, no automatic rollback) +DEPLOY_URL=https://www.fewo-stommer.de + +# Number of releases kept on the server for rollbacks +DEPLOY_KEEP=5 + +# Local build: how Composer is called (Windows example: "php /c/path/to/composer.phar") +# COMPOSER_BIN=composer diff --git a/scripts/deploy.sh b/scripts/deploy.sh new file mode 100644 index 0000000..f52d7e6 --- /dev/null +++ b/scripts/deploy.sh @@ -0,0 +1,211 @@ +#!/usr/bin/env bash +# +# Deployment to Strato (or any SSH host offering bash, tar and a PHP CLI) with atomic releases. +# +# scripts/deploy.sh setup create the folder structure on the server (once) +# scripts/deploy.sh deploy build, upload, migrate, switch, health check (rollback on failure) +# scripts/deploy.sh rollback switch back to the previous release +# scripts/deploy.sh releases list releases on the server +# scripts/deploy.sh artisan run an artisan command in the active release +# +# Settings come from scripts/deploy..env (not committed, see scripts/deploy.example.env) +# or from environment variables (CI). Server layout below DEPLOY_PATH: +# +# releases// one folder per release (code, vendor, built assets) +# shared/.env production settings – created by hand once +# shared/storage/ uploads, logs, sessions, cache – survive every release +# current -> releases/… active release; the domain's target directory is current/public +# +set -euo pipefail + +ENVIRONMENT="${1:?Bitte Umgebung angeben, z. B.: scripts/deploy.sh production deploy}" +COMMAND="${2:-deploy}" +shift $(($# >= 2 ? 2 : 1)) + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +CONFIG="$ROOT/scripts/deploy.$ENVIRONMENT.env" +if [[ -f "$CONFIG" ]]; then + # shellcheck source=/dev/null + source "$CONFIG" +fi + +: "${DEPLOY_HOST:?DEPLOY_HOST fehlt (z. B. ssh.strato.de oder local)}" +: "${DEPLOY_PATH:?DEPLOY_PATH fehlt (Ordner auf dem Server, z. B. fewo-production)}" +DEPLOY_USER="${DEPLOY_USER:-}" +DEPLOY_PORT="${DEPLOY_PORT:-22}" +DEPLOY_PHP="${DEPLOY_PHP:-/opt/RZphp84/bin/php-cli}" +DEPLOY_KEEP="${DEPLOY_KEEP:-5}" +DEPLOY_URL="${DEPLOY_URL:-}" +DEPLOY_SSH_KEY="${DEPLOY_SSH_KEY:-}" +COMPOSER_BIN="${COMPOSER_BIN:-composer}" + +say() { printf '\n\033[1;34m▶ %s\033[0m\n' "$*"; } +fail() { printf '\n\033[1;31m✗ %s\033[0m\n' "$*" >&2; exit 1; } + +# The script executed on the server. Arguments: [args…] +remote_script() { + cat <<'REMOTE' +set -euo pipefail +base="$1"; php="$2"; cmd="$3"; shift 3 +mkdir -p "$base" +cd "$base" + +switch_to() { + ln -sfn "$1" current.new + mv -Tf current.new current +} + +case "$cmd" in + setup) + mkdir -p releases shared/storage/app/public shared/storage/framework/cache/data shared/storage/framework/sessions shared/storage/framework/views shared/storage/logs + if [[ -f shared/.env ]]; then echo "shared/.env vorhanden."; else echo "HINWEIS: Bitte $base/shared/.env anlegen (Vorlage: .env.production.example)."; fi + echo "PHP: $("$php" -v | head -n 1)" + ;; + receive) + release="$1" + mkdir -p "releases/$release" + tar -xzf "upload-$release.tgz" -C "releases/$release" + rm -f "upload-$release.tgz" + ;; + activate) + release="$1"; keep="$2"; dir="releases/$release" + [[ -f shared/.env ]] || { echo "shared/.env fehlt – erst anlegen (siehe docs/DEPLOYMENT.md)." >&2; exit 1; } + rm -rf "$dir/storage" + ln -s ../../shared/storage "$dir/storage" + ln -sfn ../../shared/.env "$dir/.env" + mkdir -p "$dir/bootstrap/cache" + ln -sfn ../storage/app/public "$dir/public/storage" + ( + cd "$dir" + "$php" artisan migrate --force --no-interaction + "$php" artisan optimize --no-interaction + "$php" artisan filament:optimize --no-interaction >/dev/null 2>&1 || true + ) + readlink current > .previous_release 2>/dev/null || true + switch_to "$dir" + ls -1d releases/* | sort | head -n -"$keep" | xargs -r rm -rf + echo "Aktiv: $release" + ;; + rollback) + active="$(readlink current 2>/dev/null || true)" + target="$(cat .previous_release 2>/dev/null || true)" + if [[ -z "$target" || "$target" == "$active" || ! -d "$target" ]]; then + target="$(ls -1d releases/* | sort | grep -vx "$active" | tail -n 1 || true)" + fi + [[ -n "$target" && -d "$target" ]] || { echo "Keine frühere Version vorhanden." >&2; exit 1; } + switch_to "$target" + echo "$active" > .previous_release + echo "Zurückgeschaltet auf: $target (Datenbank-Migrationen werden dabei nicht zurückgenommen)" + ;; + releases) + ls -1 releases + echo "Aktiv: $(readlink current 2>/dev/null || echo '–')" + ;; + artisan) + cd current + "$php" artisan "$@" + ;; + *) + echo "Unbekannter Befehl: $cmd" >&2; exit 1 + ;; +esac +REMOTE +} + +run_remote() { + if [[ "$DEPLOY_HOST" == "local" ]]; then + bash -s -- "$DEPLOY_PATH" "$DEPLOY_PHP" "$@" + else + local ssh_args=(-p "$DEPLOY_PORT" -o BatchMode=yes -o ServerAliveInterval=30) + [[ -n "$DEPLOY_SSH_KEY" ]] && ssh_args+=(-i "$DEPLOY_SSH_KEY") + ssh "${ssh_args[@]}" "${DEPLOY_USER:+$DEPLOY_USER@}$DEPLOY_HOST" bash -s -- "$DEPLOY_PATH" "$DEPLOY_PHP" "$@" + fi +} + +# Runs the remote script (sent via stdin) with the given command. +remote() { + run_remote "$@" < <(remote_script) +} + +# Copies the release archive to /upload-.tgz on the server. +upload() { + local archive="$1" release="$2" + if [[ "$DEPLOY_HOST" == "local" ]]; then + mkdir -p "$DEPLOY_PATH" + cp "$archive" "$DEPLOY_PATH/upload-$release.tgz" + else + local ssh_args=(-p "$DEPLOY_PORT" -o BatchMode=yes) + [[ -n "$DEPLOY_SSH_KEY" ]] && ssh_args+=(-i "$DEPLOY_SSH_KEY") + ssh "${ssh_args[@]}" "${DEPLOY_USER:+$DEPLOY_USER@}$DEPLOY_HOST" "mkdir -p '$DEPLOY_PATH' && cat > '$DEPLOY_PATH/upload-$release.tgz'" < "$archive" + fi +} + +build() { + say "Baue Version aus Git-Stand $(git -C "$ROOT" rev-parse --short HEAD)" + if [[ -n "$(git -C "$ROOT" status --porcelain)" ]]; then + echo "Hinweis: Nicht committete Änderungen werden NICHT ausgeliefert (gebaut wird der letzte Commit)." + fi + + BUILD_DIR="$(mktemp -d)" + git -C "$ROOT" archive --format=tar HEAD | tar -x -C "$BUILD_DIR" + ( + cd "$BUILD_DIR" + $COMPOSER_BIN install --no-dev --prefer-dist --optimize-autoloader --no-interaction --no-progress + npm ci --no-audit --no-fund + npm run build + rm -rf node_modules tests docs .gitea .github scripts storage .env.example .env.production.example .ai .claude .cursor AGENTS.md CLAUDE.md boost.json phpunit.xml + git -C "$ROOT" rev-parse HEAD > REVISION + ) + ARCHIVE="$BUILD_DIR.tgz" + tar -czf "$ARCHIVE" -C "$BUILD_DIR" . + echo "Paket: $(du -h "$ARCHIVE" | cut -f1)" +} + +health_check() { + [[ -n "$DEPLOY_URL" ]] || { echo "Kein DEPLOY_URL gesetzt – Gesundheitscheck übersprungen."; return 0; } + say "Prüfe $DEPLOY_URL/up" + for attempt in 1 2 3 4 5; do + if curl -fsS --max-time 15 "$DEPLOY_URL/up" > /dev/null; then + echo "Webseite antwortet." + return 0 + fi + sleep 3 + done + return 1 +} + +case "$COMMAND" in + setup) + say "Lege Ordnerstruktur in $DEPLOY_PATH an" + remote setup + ;; + deploy) + build + RELEASE="$(date -u +%Y%m%d%H%M%S)" + say "Übertrage Version $RELEASE" + upload "$ARCHIVE" "$RELEASE" + remote receive "$RELEASE" + say "Migrieren, Caches aufwärmen, umschalten" + remote activate "$RELEASE" "$DEPLOY_KEEP" + if ! health_check; then + say "Gesundheitscheck fehlgeschlagen – schalte zurück" + remote rollback + fail "Deployment zurückgerollt. Logs: scripts/deploy.sh $ENVIRONMENT artisan about / shared/storage/logs" + fi + rm -rf "$BUILD_DIR" "$ARCHIVE" + say "Fertig: Version $RELEASE ist live." + ;; + rollback) + remote rollback + health_check || fail "Auch die vorige Version antwortet nicht – bitte Logs prüfen." + ;; + releases) + remote releases + ;; + artisan) + remote artisan "$@" + ;; + *) + fail "Unbekannter Befehl: $COMMAND (setup | deploy | rollback | releases | artisan …)" + ;; +esac diff --git a/tests/Feature/SchedulerEndpointTest.php b/tests/Feature/SchedulerEndpointTest.php new file mode 100644 index 0000000..7f45baf --- /dev/null +++ b/tests/Feature/SchedulerEndpointTest.php @@ -0,0 +1,25 @@ +get('/automation/scheduler')->assertNotFound(); + $this->get('/automation/scheduler?token=irgendwas')->assertNotFound(); + } + + public function test_scheduler_runs_with_the_configured_token(): void + { + config(['fewo.scheduler_token' => 'geheim']); + + $this->get('/automation/scheduler?token=falsch')->assertNotFound(); + $this->getJson('/automation/scheduler?token=geheim')->assertOk()->assertJsonStructure(['ran_at', 'output']); + } +}