-
Notifications
You must be signed in to change notification settings - Fork 0
434 lines (374 loc) · 15.1 KB
/
Copy pathcd-backend.yml
File metadata and controls
434 lines (374 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
name: CD - Deploy Backend
on:
push:
branches: [ main ]
paths:
- 'src/api/**'
- 'src/lib/**'
- 'Menlo.slnx'
- 'Directory.Build.props'
- 'Directory.Packages.props'
- '.github/workflows/cd-backend.yml'
- 'Dockerfile'
- 'infra/**'
workflow_dispatch:
inputs:
deploy-infra:
description: 'Deploy infrastructure before backend'
required: false
default: false
type: boolean
env:
DOTNET_VERSION: '10.0.x'
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}/menlo-api
KEY_VAULT_NAME: kv-menlo-prod
CERTIFICATE_NAME: menlo-cd-cert
jobs:
# ============================================================================
# Infrastructure Deployment (Optional)
# ============================================================================
# Only runs on workflow_dispatch with deploy-infra=true or when infra/ changes
deploy-infrastructure:
name: Deploy Infrastructure
if: |
github.event_name == 'workflow_dispatch' && inputs.deploy-infra == true ||
contains(github.event.head_commit.modified, 'infra/')
uses: ./.github/workflows/cd-infra.yml
with:
environment: Production
secrets: inherit
permissions:
id-token: write
contents: read
# ============================================================================
# Build and Push Container
# ============================================================================
build-and-push:
name: Build and Push Container
runs-on: ubuntu-latest
outputs:
image-tag: ${{ steps.meta.outputs.tags }}
permissions:
contents: read
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to Container Registry
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=sha,prefix={{branch}}-
type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push Docker image
uses: docker/build-push-action@v7
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
platforms: linux/amd64
# ============================================================================
# Download Certificate from Key Vault
# ============================================================================
# Downloads the certificate for use by the home server deployment
download-certificate:
name: Download Certificate
runs-on: ubuntu-latest
needs: [build-and-push]
permissions:
id-token: write
contents: read
outputs:
certificate-path: ${{ steps.download.outputs.certificate-path }}
certificate-thumbprint: ${{ steps.download.outputs.thumbprint }}
steps:
- name: Azure Login (OIDC)
uses: azure/login@v3
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- name: Download Certificate from Key Vault
id: download
uses: azure/cli@v3
with:
azcliversion: latest
inlineScript: |
echo "🔐 Downloading certificate from Key Vault..."
# Download the certificate (PFX format with private key)
az keyvault secret download \
--vault-name "${{ env.KEY_VAULT_NAME }}" \
--name "${{ env.CERTIFICATE_NAME }}" \
--encoding base64 \
--file cert.pfx
# Get the thumbprint
THUMBPRINT=$(az keyvault certificate show \
--vault-name "${{ env.KEY_VAULT_NAME }}" \
--name "${{ env.CERTIFICATE_NAME }}" \
--query "x509ThumbprintHex" \
--output tsv)
echo "✅ Certificate downloaded successfully"
echo " Thumbprint: $THUMBPRINT"
echo "thumbprint=$THUMBPRINT" >> "$GITHUB_OUTPUT"
# The certificate will be passed to the next job via artifact
echo "certificate-path=cert.pfx" >> "$GITHUB_OUTPUT"
- name: Upload Certificate Artifact
uses: actions/upload-artifact@v7
with:
name: certificate
path: cert.pfx
retention-days: 1
if-no-files-found: error
# ============================================================================
# Deploy to Home Server
# ============================================================================
deploy-to-home-server:
name: Deploy to Home Server
runs-on: self-hosted
needs: [build-and-push, download-certificate]
environment:
name: 'Production'
steps:
- name: Checkout deployment scripts
uses: actions/checkout@v6
with:
sparse-checkout: |
deployment/
- name: Download Certificate Artifact
uses: actions/download-artifact@v8
with:
name: certificate
path: ${{ runner.temp }}/cert
- name: Deploy application
shell: pwsh
env:
IMAGE_TAG: ${{ needs.build-and-push.outputs.image-tag }}
CERTIFICATE_THUMBPRINT: ${{ needs.download-certificate.outputs.certificate-thumbprint }}
CERTIFICATE_PATH: ${{ runner.temp }}/cert/cert.pfx
AZURE_AD_INSTANCE: ${{ vars.AZURE_AD_INSTANCE }}
AZURE_AD_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_AD_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID_PROD }}
FEATURES_BUDGET: ${{ vars.FEATURES_BUDGET || 'true' }}
run: |
$ErrorActionPreference = "Stop"
Write-Host "🚀 Starting Menlo deployment..." -ForegroundColor Green
# Extract the first tag (main image tag) from the multi-line output
$imageTag = ($env:IMAGE_TAG -split "`n")[0].Trim()
Write-Host "📦 Using image: $imageTag" -ForegroundColor Cyan
# Set environment variables
$env:POSTGRES_USER = "${{ secrets.POSTGRES_USER }}"
$env:POSTGRES_PASSWORD = "${{ secrets.POSTGRES_PASSWORD }}"
$env:POSTGRES_DB = "menlo"
# Application paths
$AppPath = "$env:USERPROFILE\menlo"
New-Item -ItemType Directory -Path $AppPath -Force | Out-Null
Set-Location $AppPath
# Encode certificate as Base64 for passing to container
Write-Host "📜 Encoding certificate..." -ForegroundColor Yellow
$CertBase64 = [Convert]::ToBase64String([System.IO.File]::ReadAllBytes("$env:CERTIFICATE_PATH"))
# Create docker-compose.prod.yml
$composeContent = @"
version: '3.8'
services:
menlo-api:
image: $imageTag
container_name: menlo-api
restart: unless-stopped
environment:
- ASPNETCORE_ENVIRONMENT=Production
- ASPNETCORE_URLS=http://+:8080
- ConnectionStrings__menlo=Host=postgres;Database=menlo;Username=$env:POSTGRES_USER;Password=$env:POSTGRES_PASSWORD;SSL Mode=Disable
- Ollama__BaseUrl=http://ollama:11434
- Logging__LogLevel__Default=Information
- Features__Budget=$env:FEATURES_BUDGET
- AzureAd__Instance=$env:AZURE_AD_INSTANCE
- AzureAd__TenantId=$env:AZURE_AD_TENANT_ID
- AzureAd__ClientId=$env:AZURE_AD_CLIENT_ID
- AzureAd__ClientCertificates__0__SourceType=Base64Encoded
- AzureAd__ClientCertificates__0__Base64EncodedValue=${CertBase64}
ports:
- "8080:8080"
networks:
- menlo-network
depends_on:
- postgres
- ollama
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:8080/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
postgres:
image: postgres:17
container_name: menlo-postgres
restart: unless-stopped
environment:
- POSTGRES_DB=menlo
- POSTGRES_USER=$env:POSTGRES_USER
- POSTGRES_PASSWORD=$env:POSTGRES_PASSWORD
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
networks:
- menlo-network
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $env:POSTGRES_USER -d menlo"]
interval: 30s
timeout: 10s
retries: 5
ollama:
image: ollama/ollama:latest
container_name: menlo-ollama
restart: unless-stopped
volumes:
- ollama_data:/root/.ollama
ports:
- "11434:11434"
networks:
- menlo-network
environment:
- OLLAMA_KEEP_ALIVE=24h
- OLLAMA_NUM_PARALLEL=2
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:11434/api/tags || exit 1"]
interval: 60s
timeout: 30s
retries: 3
start_period: 120s
volumes:
postgres_data:
name: menlo_postgres_data
ollama_data:
name: menlo_ollama_data
networks:
menlo-network:
name: menlo_network
driver: bridge
"@
$composeContent | Out-File -FilePath "docker-compose.prod.yml" -Encoding UTF8
# Pull new image
Write-Host "📥 Pulling new image..." -ForegroundColor Yellow
podman pull "$imageTag"
# Stop existing services
Write-Host "⏸️ Stopping existing services..." -ForegroundColor Yellow
podman compose -f docker-compose.prod.yml down 2>$null
# Start services
Write-Host "▶️ Starting services..." -ForegroundColor Yellow
podman compose -f docker-compose.prod.yml up -d
# Wait for health checks
Write-Host "🏥 Waiting for services..." -ForegroundColor Yellow
Start-Sleep -Seconds 30
# Check service status
Write-Host "📊 Service Status:" -ForegroundColor Cyan
podman compose -f docker-compose.prod.yml ps
Write-Host "✅ Deployment completed!" -ForegroundColor Green
- name: Verify deployment
shell: pwsh
run: |
Write-Host "🔍 Verifying deployment..." -ForegroundColor Yellow
Start-Sleep -Seconds 30
# Test API health
for ($i = 1; $i -le 5; $i++) {
try {
$response = Invoke-WebRequest -Uri 'http://localhost:8080/health' -TimeoutSec 5 -UseBasicParsing
if ($response.StatusCode -eq 200) {
Write-Host "✅ API health check passed" -ForegroundColor Green
break
}
} catch {
Write-Host "⏳ API not ready yet... ($i/5)" -ForegroundColor Yellow
Start-Sleep -Seconds 10
}
}
- name: Update Cloudflare Tunnel
if: vars.CLOUDFLARE_TUNNEL_ENABLED == 'true'
shell: pwsh
run: |
Write-Host "🌐 Restarting Cloudflare Tunnel..." -ForegroundColor Yellow
# Restart cloudflared service if running
try {
$service = Get-Service cloudflared -ErrorAction SilentlyContinue
if ($service) {
Restart-Service cloudflared -Force
Write-Host "✅ Cloudflare Tunnel restarted" -ForegroundColor Green
} else {
Write-Host "⚠️ Cloudflare Tunnel service not found" -ForegroundColor Yellow
}
} catch {
Write-Host "❌ Failed to restart Cloudflare Tunnel: $_" -ForegroundColor Red
}
post-deployment:
name: Post-Deployment Checks
runs-on: ubuntu-latest
needs: [build-and-push, deploy-to-home-server]
if: success()
steps:
- name: External health check
run: |
echo "🏥 Running external health check..."
if [[ -n "${{ vars.DOMAIN }}" && -n "${{ vars.SUBDOMAIN }}" ]]; then
API_URL="https://${{ vars.SUBDOMAIN }}.${{ vars.DOMAIN }}"
# Wait for Cloudflare tunnel to stabilize
sleep 60
# Check external API health
for i in {1..3}; do
if curl -f "$API_URL/health" -H "User-Agent: GitHub-Actions-Health-Check" -s; then
echo "✅ External API health check passed for $API_URL"
break
else
echo "⏳ External API at $API_URL not ready yet... ($i/3)"
sleep 30
fi
done
elif [[ -n "${{ vars.API_BASE_URL }}" ]]; then
# Fallback to legacy API_BASE_URL variable
sleep 60
# Check external API health
for i in {1..3}; do
if curl -f "${{ vars.API_BASE_URL }}/health" -H "User-Agent: GitHub-Actions-Health-Check" -s; then
echo "✅ External API health check passed"
break
else
echo "⏳ External API not ready yet... ($i/3)"
sleep 30
fi
done
else
echo "⚠️ Domain variables (DOMAIN, SUBDOMAIN) or API_BASE_URL not configured, skipping external health check"
fi
- name: Deployment summary
env:
IMAGE_TAG: ${{ needs.build-and-push.outputs.image-tag }}
run: |
# Extract the first tag (main image tag) from the multi-line output
IMAGE_TAG_CLEAN=$(echo "$IMAGE_TAG" | head -n1 | xargs)
echo "### 🚀 Deployment Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "- **Environment**: Home" >> $GITHUB_STEP_SUMMARY
echo "- **Server**: ${{ secrets.HOME_SERVER_HOST }}" >> $GITHUB_STEP_SUMMARY
echo "- **Image**: $IMAGE_TAG_CLEAN" >> $GITHUB_STEP_SUMMARY
echo "- **Deployed By**: ${{ github.actor }}" >> $GITHUB_STEP_SUMMARY
echo "- **Commit**: [${{ github.sha }}](${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }})" >> $GITHUB_STEP_SUMMARY
if [[ -n "${{ vars.DOMAIN }}" && -n "${{ vars.SUBDOMAIN }}" ]]; then
echo "- **External URL**: https://${{ vars.SUBDOMAIN }}.${{ vars.DOMAIN }}" >> $GITHUB_STEP_SUMMARY
elif [[ -n "${{ vars.API_BASE_URL }}" ]]; then
echo "- **External URL**: ${{ vars.API_BASE_URL }}" >> $GITHUB_STEP_SUMMARY
fi