initial commit

Change-Id: I00b172586748254398022a27ff639ec675d04840
This commit is contained in:
Scaffolder
2026-05-05 16:40:41 +00:00
commit 4c741822bc
135 changed files with 27590 additions and 0 deletions

View File

@@ -0,0 +1,84 @@
name: Build and Push to ACR
on:
push:
branches: [ dev ]
workflow_dispatch: {}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
AZURE_FEDERATED_TOKEN_FILE: /var/run/secrets/azure/tokens/azure-identity-token
jobs:
build:
name: Build and Push
runs-on: ubuntu-latest
if: >-
github.ref != 'refs/heads/main' && (
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'push' && github.event.before != '0000000000000000000000000000000000000000')
)
permissions:
contents: read
id-token: write
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install Azure CLI
run: |
command -v az &>/dev/null || curl -sL https://aka.ms/InstallAzureCLIDeb | bash
- name: Install Docker CLI
run: |
command -v docker &>/dev/null || (apt-get update -qq && apt-get install -y docker.io)
docker --version
- name: Azure login (OIDC)
run: |
az login \
--service-principal \
--username "$AZURE_CLIENT_ID" \
--tenant "$AZURE_TENANT_ID" \
--federated-token "$(cat $AZURE_FEDERATED_TOKEN_FILE)"
echo "✓ Azure login successful"
- name: Get ACR details
run: |
ACR_NAME=$(az acr list --query "[0].name" -o tsv)
ACR_NAME="${ACR_NAME:-bstagecjotdevacr}"
echo "ACR_NAME=$ACR_NAME" >> $GITHUB_ENV
echo "ACR_LOGIN_SERVER=${ACR_NAME}.azurecr.io" >> $GITHUB_ENV
echo "✓ Using ACR: ${ACR_NAME}.azurecr.io"
- name: ACR Login
run: |
ACR_TOKEN=$(az acr login --name "$ACR_NAME" --expose-token --output tsv --query accessToken)
docker login "$ACR_LOGIN_SERVER" \
--username 00000000-0000-0000-0000-000000000000 \
--password "$ACR_TOKEN"
echo "✓ ACR login successful"
- name: Build and Push Docker image
run: |
IMAGE_TAG="${{ gitea.sha }}"
IMAGE_FULL="${ACR_LOGIN_SERVER}/demo-kpc-2:${IMAGE_TAG}"
IMAGE_LATEST="${ACR_LOGIN_SERVER}/demo-kpc-2:latest"
docker build -t "$IMAGE_FULL" -t "$IMAGE_LATEST" .
docker push "$IMAGE_FULL"
docker push "$IMAGE_LATEST"
echo "IMAGE_FULL=$IMAGE_FULL" >> $GITHUB_ENV
echo "✓ Pushed: $IMAGE_FULL"
- name: Build Summary
run: |
echo "### ✅ Build Successful" >> $GITHUB_STEP_SUMMARY
echo "| | |" >> $GITHUB_STEP_SUMMARY
echo "|---|---|" >> $GITHUB_STEP_SUMMARY
echo "| **Service** | demo-kpc-2 |" >> $GITHUB_STEP_SUMMARY
echo "| **Commit** | ${{ gitea.sha }} |" >> $GITHUB_STEP_SUMMARY
echo "| **Image** | $IMAGE_FULL |" >> $GITHUB_STEP_SUMMARY

113
.gitea/workflows/deploy.yml Normal file
View File

@@ -0,0 +1,113 @@
name: Deploy to Humanitec v2
on:
workflow_run:
workflows: ["Build and Push to ACR"]
types: [completed]
branches: [ "dev", "staging", "prod" ]
workflow_dispatch:
inputs:
environment:
description: 'Target environment'
required: true
default: 'dev'
type: choice
options:
- dev
- staging
- prod
env:
HUMANITEC_ORG: skillful-wild-chicken-2617
PROJECT_ID: demo-kpc-2
HUMANITEC_TOKEN: ${{ secrets.HUMANITEC_TOKEN }}
HUMANITEC_AUTH_TOKEN: ${{ secrets.HUMANITEC_TOKEN }}
HUMANITEC_API_PREFIX: https://api.humanitec.dev
jobs:
guard:
name: Platform guard
runs-on: ubuntu-latest
outputs:
ready: ${{ steps.check.outputs.ready }}
steps:
- uses: actions/checkout@v4
- name: Check platform initialized
id: check
run: |
if [ -f ".platform/initialized.md" ]; then
echo "ready=true" >> $GITHUB_OUTPUT
else
echo "ready=false" >> $GITHUB_OUTPUT
echo "Skipping: .platform/initialized.md not found"
fi
deploy:
name: Deploy to Humanitec v2
needs: guard
if: >-
(github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && needs.guard.outputs.ready == 'true') ||
(github.event_name == 'workflow_dispatch')
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Install hctl CLI
run: |
if ! command -v jq &>/dev/null; then
apt-get update -qq && apt-get install -y -qq jq
fi
HCTL_VERSION=$(curl -s https://api.github.com/repos/humanitec/hctl/releases/latest | jq -r '.tag_name')
mkdir -p /tmp/hctl-install
curl -sLo /tmp/hctl-install/hctl.tar.gz "https://github.com/humanitec/hctl/releases/download/${HCTL_VERSION}/hctl_${HCTL_VERSION#v}_linux_amd64.tar.gz"
tar -xzf /tmp/hctl-install/hctl.tar.gz -C /tmp/hctl-install
install -m 755 /tmp/hctl-install/hctl /usr/local/bin/hctl
hctl --version
- name: Derive environment
run: |
DISPATCH_ENV="${{ github.event.inputs.environment }}"
if [ -n "$DISPATCH_ENV" ]; then
ENV_ID="$DISPATCH_ENV"
else
# workflow_run: derive from upstream build-push branch
BRANCH="${{ github.event.workflow_run.head_branch }}"
BRANCH="${BRANCH:-${GITHUB_REF_NAME}}"
case "$BRANCH" in
dev) ENV_ID="dev" ;;
staging) ENV_ID="staging" ;;
prod) ENV_ID="prod" ;;
*) ENV_ID="dev" ;;
esac
fi
echo "ENV_ID=$ENV_ID" >> $GITHUB_ENV
echo "Deploying to environment: $ENV_ID"
- name: Deploy with Score
run: |
MAX_RETRIES=8
RETRY_DELAY=30
attempt=0
until hctl score deploy "$PROJECT_ID" "$ENV_ID" score.yaml --no-prompt; do
attempt=$((attempt + 1))
if [[ $attempt -ge $MAX_RETRIES ]]; then
echo "All $MAX_RETRIES deploy attempts failed."
exit 1
fi
echo "Attempt $attempt failed. Retrying in ${RETRY_DELAY}s..."
sleep $RETRY_DELAY
done
echo "Deployment successful!"
- name: Deployment summary
if: always()
run: |
SHORT_SHA="${GITHUB_SHA:0:7}"
echo "## Deployment Result" >> $GITHUB_STEP_SUMMARY
echo "| Field | Value |" >> $GITHUB_STEP_SUMMARY
echo "|---|---|" >> $GITHUB_STEP_SUMMARY
echo "| Project | \`$PROJECT_ID\` |" >> $GITHUB_STEP_SUMMARY
echo "| Environment | \`$ENV_ID\` |" >> $GITHUB_STEP_SUMMARY
echo "| Commit | \`$SHORT_SHA\` |" >> $GITHUB_STEP_SUMMARY
echo "[View in Humanitec Console](https://console.humanitec.dev/orgs/$HUMANITEC_ORG/projects/$PROJECT_ID/environments/$ENV_ID)" >> $GITHUB_STEP_SUMMARY

View File

@@ -0,0 +1,133 @@
name: Integration Test
on:
pull_request:
branches: [ "main" ]
workflow_dispatch: {}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
# ── Job 1: Platform Conformance ───────────────────────────────────────────
platform-check:
name: Platform Conformance
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Validate catalog-info.yaml
run: |
if [ ! -f catalog-info.yaml ]; then
echo "✗ catalog-info.yaml not found"
exit 1
fi
python3 -c "import yaml; list(yaml.safe_load_all(open('catalog-info.yaml')))" 2>/dev/null \
|| (pip install pyyaml -q && python3 -c "import yaml; list(yaml.safe_load_all(open('catalog-info.yaml')))")
echo "✓ catalog-info.yaml is valid YAML"
- name: Check platform initialized
run: |
if [ -f ".platform/initialized.md" ]; then
echo "✓ Platform initialized"
else
echo "⚠ .platform/initialized.md not found — skipping guard"
fi
# ── Job 2: Unit Tests + Container Smoke ───────────────────────────────────
smoke-test:
name: Unit Tests + Container Smoke
runs-on: ubuntu-latest
needs: platform-check
timeout-minutes: 20
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Free disk space
run: |
docker system prune -f 2>/dev/null || true
df -h / 2>/dev/null || true
- name: Install Docker CLI
run: command -v docker &>/dev/null || (apt-get update -qq && apt-get install -y docker.io)
- name: Build container image
run: |
if [ -f Dockerfile ]; then
docker build -t ci-image:test .
else
echo "No Dockerfile found — skipping container smoke test"
echo "SKIP_SMOKE=true" >> $GITHUB_ENV
fi
- name: Start service and wait for health
if: env.SKIP_SMOKE != 'true'
run: |
CONTAINER_NAME="ci-${GITHUB_RUN_ID}"
PORT="${CONTAINER_PORT:-8080}"
HEALTH_PATH="${HEALTH_ENDPOINT:-/health}"
echo "CONTAINER_NAME=${CONTAINER_NAME}" >> $GITHUB_ENV
echo "CONTAINER_PORT=${PORT}" >> $GITHUB_ENV
echo "HEALTH_PATH=${HEALTH_PATH}" >> $GITHUB_ENV
docker run -d --name "${CONTAINER_NAME}" -e OTEL_SDK_DISABLED=true ci-image:test
for i in $(seq 1 10); do
CONTAINER_IP=$(docker inspect "${CONTAINER_NAME}" --format '{{.NetworkSettings.IPAddress}}' 2>/dev/null)
[ -n "${CONTAINER_IP}" ] && break
sleep 1
done
echo "CONTAINER_IP=${CONTAINER_IP}" >> $GITHUB_ENV
echo "Waiting for ${HEALTH_PATH} on ${CONTAINER_IP}:${PORT} (up to 180s)..."
DEADLINE=$(($(date +%s) + 180))
while true; do
if curl -sf "http://${CONTAINER_IP}:${PORT}${HEALTH_PATH}" >/dev/null 2>&1; then
break
fi
if [ $(date +%s) -ge $DEADLINE ]; then
echo "Timeout waiting for health check"
docker logs "${CONTAINER_NAME}" 2>&1 | tail -30
exit 1
fi
if ! docker ps --filter "name=${CONTAINER_NAME}" --format '{{.Status}}' | grep -q Up; then
echo "Container exited:"
docker logs "${CONTAINER_NAME}" 2>&1 | tail -30
exit 1
fi
echo " still waiting..."; sleep 3
done
echo "✓ Service healthy at ${CONTAINER_IP}:${PORT}${HEALTH_PATH}"
- name: Validate health response
if: env.SKIP_SMOKE != 'true'
run: |
curl -sf "http://${CONTAINER_IP}:${CONTAINER_PORT}${HEALTH_PATH}" > /tmp/health.json
echo "Health response:"
cat /tmp/health.json
echo ""
echo "✓ Container smoke test: PASSED"
- name: Cleanup
if: always()
run: docker rm -f "ci-${GITHUB_RUN_ID}" 2>/dev/null || true
- name: Post commit status
if: always()
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
JOB_STATUS: ${{ job.status }}
run: |
STATE=$([[ "$JOB_STATUS" == "success" ]] && echo "success" || echo "failure")
DESC=$([[ "$STATE" == "success" ]] && echo "All checks passed" || echo "Some checks failed")
curl -sf -X POST \
-H "Authorization: token ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
"${GITHUB_SERVER_URL}/api/v1/repos/${GITHUB_REPOSITORY}/statuses/${GITHUB_SHA}" \
-d "{\"state\":\"${STATE}\",\"context\":\"Integration Test / Unit Tests + Container Smoke (workflow_dispatch)\",\"description\":\"${DESC}\"}" \
|| true

224
.gitea/workflows/sonar.yaml Normal file
View File

@@ -0,0 +1,224 @@
name: SonarQube Analysis
on:
pull_request:
types: [opened, synchronize, reopened]
concurrency:
group: ${{ gitea.workflow }}-${{ gitea.ref }}
cancel-in-progress: true
jobs:
sonarqube:
name: Build, Test & Analyse
runs-on: ubuntu-latest
timeout-minutes: 15
env:
SONAR_PROJECT_KEY: demo-kpc-2
SONAR_ADMIN_TOKEN: ${{ secrets.SONAR_ADMIN_TOKEN }}
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
BACKSTAGE_CLEANUP_TOKEN: ${{ secrets.BACKSTAGE_CLEANUP_TOKEN }}
BACKSTAGE_URL: https://dev.backstage.kyndemo.live
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: '17'
distribution: 'temurin'
- name: Make Maven wrapper executable
run: chmod +x mvnw
- name: Cache Maven packages
uses: actions/cache@v4
with:
path: ~/.m2/repository
key: maven-${{ runner.os }}-${{ hashFiles('**/pom.xml') }}
restore-keys: maven-${{ runner.os }}-
- name: Cache SonarQube analysis data
uses: actions/cache@v4
with:
path: ~/.sonar/cache
key: sonar-${{ runner.os }}-${{ hashFiles('**/pom.xml') }}
restore-keys: sonar-${{ runner.os }}-
- name: Validate required secrets
run: |
[[ -n "$SONAR_ADMIN_TOKEN" ]] || { echo "::error::SONAR_ADMIN_TOKEN is not set"; exit 1; }
[[ -n "$SONAR_HOST_URL" ]] || { echo "::error::SONAR_HOST_URL is not set"; exit 1; }
[[ -n "$SONAR_PROJECT_KEY" ]] || { echo "::error::SONAR_PROJECT_KEY is not set"; exit 1; }
SONAR_HOST_URL="${SONAR_HOST_URL%/}"
AUTH_RESPONSE=$(curl -s -o /tmp/sonar-auth-response.json -w "%{http_code}" \
-u "${SONAR_ADMIN_TOKEN}:" \
"${SONAR_HOST_URL}/api/authentication/validate")
if [[ "$AUTH_RESPONSE" != "200" ]]; then
echo "::error::SonarQube is unreachable or returned HTTP ${AUTH_RESPONSE} — check SONAR_HOST_URL"
exit 1
fi
TOKEN_VALID=$(jq -r '.valid' /tmp/sonar-auth-response.json 2>/dev/null || echo "false")
if [[ "$TOKEN_VALID" != "true" ]]; then
echo "::error::SONAR_ADMIN_TOKEN is invalid or has been revoked (SonarQube returned valid=false)"
exit 1
fi
echo "✅ SONAR_ADMIN_TOKEN verified against ${SONAR_HOST_URL}"
- name: Bootstrap SonarQube project and generate scan token
id: sonar-bootstrap
run: |
PROJECT_COUNT=$(curl -sf \
-u "${SONAR_ADMIN_TOKEN}:" \
"${SONAR_HOST_URL}/api/projects/search?projects=${SONAR_PROJECT_KEY}" \
| jq '.paging.total')
if [[ "$PROJECT_COUNT" == "0" ]]; then
echo "Project '${SONAR_PROJECT_KEY}' not found — creating it..."
curl -sf -X POST \
-u "${SONAR_ADMIN_TOKEN}:" \
"${SONAR_HOST_URL}/api/projects/create" \
--data-urlencode "name=${SONAR_PROJECT_KEY}" \
--data-urlencode "project=${SONAR_PROJECT_KEY}" \
--data-urlencode "mainBranch=main" \
--data-urlencode "visibility=private"
echo "✅ Project created."
else
echo "✅ Project '${SONAR_PROJECT_KEY}' already exists — skipping creation."
fi
TOKEN_NAME="gitea-scan-${SONAR_PROJECT_KEY}"
curl -sf -X POST \
-u "${SONAR_ADMIN_TOKEN}:" \
"${SONAR_HOST_URL}/api/user_tokens/revoke" \
--data-urlencode "name=${TOKEN_NAME}" \
> /dev/null 2>&1 || true
SCAN_TOKEN=$(curl -sf -X POST \
-u "${SONAR_ADMIN_TOKEN}:" \
"${SONAR_HOST_URL}/api/user_tokens/generate" \
--data-urlencode "name=${TOKEN_NAME}" \
--data-urlencode "type=PROJECT_ANALYSIS_TOKEN" \
--data-urlencode "projectKey=${SONAR_PROJECT_KEY}" \
| jq -r '.token')
[[ -n "$SCAN_TOKEN" ]] || { echo "::error::Failed to generate scan token"; exit 1; }
echo "✅ Scan token generated for project '${SONAR_PROJECT_KEY}'"
echo "::add-mask::${SCAN_TOKEN}"
echo "SCAN_TOKEN=${SCAN_TOKEN}" >> "$GITHUB_ENV"
- name: Build and test
run: |
./mvnw -B verify \
-Dtest='!PostgresIntegrationTests,!MySqlIntegrationTests'
- name: SonarQube analysis
run: |
./mvnw -B org.sonarsource.scanner.maven:sonar-maven-plugin:4.0.0.4121:sonar \
-Dsonar.projectKey="${SONAR_PROJECT_KEY}" \
-Dsonar.host.url="${SONAR_HOST_URL}" \
-Dsonar.token="${SCAN_TOKEN}" \
-Dsonar.java.source=17 \
-Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
- name: Quality Gate check
id: quality-gate
run: |
echo "Waiting for SonarQube to process the analysis..."
for i in $(seq 1 24); do
RESPONSE=$(curl -sf -u "${SCAN_TOKEN}:" \
"${SONAR_HOST_URL}/api/qualitygates/project_status?projectKey=${SONAR_PROJECT_KEY}" || true)
STATUS=$(echo "$RESPONSE" | jq -r '.projectStatus.status' 2>/dev/null || echo "NONE")
if [[ "$STATUS" =~ ^(OK|ERROR|WARN)$ ]]; then break; fi
echo " Status: ${STATUS:-pending} — retrying in 5s..."
sleep 5
done
echo ""
echo "══════════════════════════════════════════"
echo " Quality Gate: $STATUS"
echo "══════════════════════════════════════════"
echo "$RESPONSE" | jq -r '
.projectStatus.conditions[] |
if .status == "ERROR" then " ❌ \(.metricKey): \(.actualValue) (threshold: \(.errorThreshold), comparator: \(.comparator))"
elif .status == "WARN" then " ⚠️ \(.metricKey): \(.actualValue) (threshold: \(.errorThreshold), comparator: \(.comparator))"
else " ✅ \(.metricKey): \(.actualValue)"
end'
echo "══════════════════════════════════════════"
FAILED=$(echo "$RESPONSE" | jq '[.projectStatus.conditions[] | select(.status == "ERROR")] | length')
if [[ "$FAILED" -gt 0 ]]; then
echo "::error::Quality Gate FAILED — $FAILED metric(s) did not meet threshold"
exit 1
fi
- name: Notify Backstage on quality gate failure
if: always() && steps.quality-gate.outcome == 'failure'
run: |
echo "--- Backstage notification debug ---"
echo "BACKSTAGE_URL: ${BACKSTAGE_URL:-<not set>}"
echo "BACKSTAGE_CLEANUP_TOKEN set: $([[ -n "$BACKSTAGE_CLEANUP_TOKEN" ]] && echo yes || echo no)"
echo "SONAR_PROJECT_KEY: ${SONAR_PROJECT_KEY:-<not set>}"
echo "GITHUB_HEAD_REF: ${GITHUB_HEAD_REF:-<not set>}"
if [[ -z "$BACKSTAGE_URL" ]]; then
echo "::error::BACKSTAGE_URL is not set — cannot send notification"
exit 0
fi
if [[ -z "$BACKSTAGE_CLEANUP_TOKEN" ]]; then
echo "::error::BACKSTAGE_CLEANUP_TOKEN is not set — cannot send notification"
exit 0
fi
PAYLOAD="{
\"recipients\": { \"type\": \"entity\", \"entityRef\": \"group:default/platform-engineering\" },
\"payload\": {
\"title\": \"SonarQube Quality Gate Failed\",
"description": "Quality gate failed for ${SONAR_PROJECT_KEY} on branch ${GITHUB_HEAD_REF}.",
\"link\": \"${SONAR_HOST_URL}/dashboard?id=${SONAR_PROJECT_KEY}\",
\"severity\": \"high\",
\"topic\": \"sonarqube-quality-gate\"
}
}"
echo "Sending notification to: ${BACKSTAGE_URL}/api/notifications"
HTTP_CODE=$(curl -s -o /tmp/bs-notify-response.json -w "%{http_code}" \
-X POST "${BACKSTAGE_URL}/api/notifications" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${BACKSTAGE_CLEANUP_TOKEN}" \
-d "${PAYLOAD}")
echo "HTTP response code: ${HTTP_CODE}"
echo "Response body:"
cat /tmp/bs-notify-response.json 2>/dev/null || echo "<empty response>"
if [[ "$HTTP_CODE" -ge 200 && "$HTTP_CODE" -lt 300 ]]; then
echo "✅ Backstage notification sent"
else
echo "⚠️ Backstage notification failed (HTTP ${HTTP_CODE})"
fi
- name: Revoke scan token
if: always()
run: |
curl -sf -X POST \
-u "${SONAR_ADMIN_TOKEN}:" \
"${SONAR_HOST_URL}/api/user_tokens/revoke" \
--data-urlencode "name=gitea-scan-${SONAR_PROJECT_KEY}" \
&& echo "✅ Scan token revoked" \
|| echo "⚠️ Token revocation failed"