Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0e2e5cba34 | ||
|
|
4277e0774e | ||
|
|
19e550df12 | ||
|
|
1704b5c61a | ||
|
|
7f568516d1 | ||
|
|
bb5b9f3026 | ||
|
|
88ae7f9158 | ||
|
|
40288eade8 |
Vendored
+257
-14
@@ -1,29 +1,272 @@
|
|||||||
|
// Pull requests run tests and checks only. On main, a change to pricing/,
|
||||||
|
// ansible/ or this file builds one image and promotes its digest from staging
|
||||||
|
// to production after a human approval. Setting RELEASE_RECORD redeploys an
|
||||||
|
// existing release without building, which is how rollback and recovery run.
|
||||||
|
|
||||||
|
// Applies one release record with Ansible on the delivery agent.
|
||||||
|
def deploy(String record, String label) {
|
||||||
|
withCredentials([sshUserPrivateKey(credentialsId: 'delivery-ssh', keyFileVariable: 'SSH_KEY')]) {
|
||||||
|
withEnv(["RECORD=${record}", "LABEL=${label}"]) {
|
||||||
|
sh '''#!/bin/bash
|
||||||
|
set -euo pipefail
|
||||||
|
mkdir -p reports
|
||||||
|
export ANSIBLE_COLLECTIONS_PATH="$WORKSPACE/.collections"
|
||||||
|
"$TOOLS/ansible-galaxy" collection install -r ansible/requirements.yml -p "$ANSIBLE_COLLECTIONS_PATH"
|
||||||
|
"$TOOLS/ansible-playbook" -i ansible/inventory.ini ansible/deploy.yml --syntax-check
|
||||||
|
echo "deploy start: $(date -u +%FT%TZ) $RECORD"
|
||||||
|
"$TOOLS/ansible-playbook" -i ansible/inventory.ini ansible/deploy.yml \
|
||||||
|
--private-key "$SSH_KEY" -e "@$RECORD" | tee "reports/$LABEL.txt"
|
||||||
|
echo "deploy end: $(date -u +%FT%TZ) $RECORD"
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prints the public behavior of a release as evidence; Ansible asserts it.
|
||||||
|
def smoke(String record) {
|
||||||
|
withEnv(["RECORD=${record}"]) {
|
||||||
|
sh '''#!/bin/bash
|
||||||
|
set -euo pipefail
|
||||||
|
URL=$(sed -n 's/^public_url: //p' "$RECORD")
|
||||||
|
curl -fsS "$URL/"; curl -fsS "$URL/health"; curl -fsS "$URL/price?quantity=3"
|
||||||
|
test "$(curl -s -o /dev/null -w '%{http_code}' "$URL/price?quantity=0")" = 400
|
||||||
|
echo "invalid quantity returned 400"
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pipeline {
|
pipeline {
|
||||||
agent any
|
agent none
|
||||||
|
|
||||||
|
options {
|
||||||
|
disableConcurrentBuilds()
|
||||||
|
skipDefaultCheckout()
|
||||||
|
}
|
||||||
|
|
||||||
|
parameters {
|
||||||
|
string(name: 'RELEASE_RECORD', defaultValue: '', description: 'Redeploy this record without building, for example releases/v1-production.yml.')
|
||||||
|
string(name: 'CONFIG_REF', defaultValue: '', description: 'Commit whose ansible/ directory to use. Empty uses this build\'s commit. Production accepts only commits on main.')
|
||||||
|
}
|
||||||
|
|
||||||
|
environment {
|
||||||
|
IMAGE = 'git.pollefeys.dev/seatbacktrivia/pricing'
|
||||||
|
TOOLS = '/opt/delivery/bin'
|
||||||
|
TRIVY_CACHE_DIR = '/home/jenkins/agent/trivy-cache'
|
||||||
|
}
|
||||||
|
|
||||||
stages {
|
stages {
|
||||||
stage('Checkout') {
|
stage('Product tests') {
|
||||||
|
agent { label 'built-in' }
|
||||||
|
when { expression { !params.RELEASE_RECORD } }
|
||||||
steps {
|
steps {
|
||||||
checkout scm
|
checkout scm
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Verify Node.js') {
|
|
||||||
steps {
|
|
||||||
sh 'node --version'
|
sh 'node --version'
|
||||||
sh 'npm --version'
|
sh 'npm --version'
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
stage('Install Dependencies') {
|
|
||||||
steps {
|
|
||||||
sh 'npm ci'
|
sh 'npm ci'
|
||||||
|
sh 'npm test'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
stage('Test') {
|
stage('Pricing tests') {
|
||||||
|
agent { label 'delivery' }
|
||||||
|
when { expression { !params.RELEASE_RECORD } }
|
||||||
steps {
|
steps {
|
||||||
sh 'npm test'
|
script {
|
||||||
|
env.RELEASE_COMMIT = checkout(scm).GIT_COMMIT
|
||||||
|
}
|
||||||
|
dir('pricing') {
|
||||||
|
sh '''
|
||||||
|
python3 -m venv .venv
|
||||||
|
. .venv/bin/activate
|
||||||
|
pip install --quiet --disable-pip-version-check -r requirements.txt
|
||||||
|
python -m py_compile app.py test_app.py
|
||||||
|
python -m unittest -v
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Dependency and secret checks') {
|
||||||
|
agent { label 'delivery' }
|
||||||
|
when { expression { !params.RELEASE_RECORD } }
|
||||||
|
steps {
|
||||||
|
sh '''
|
||||||
|
mkdir -p reports
|
||||||
|
trivy --version
|
||||||
|
trivy fs --scanners secret --skip-dirs pricing/.venv --exit-code 1 --no-progress --output reports/secrets.txt . \
|
||||||
|
|| { cat reports/secrets.txt; exit 1; }
|
||||||
|
"$TOOLS/pip-audit" --version
|
||||||
|
"$TOOLS/pip-audit" -r pricing/requirements.txt --no-deps --disable-pip > reports/pip-audit.txt 2>&1 \
|
||||||
|
|| { cat reports/pip-audit.txt; exit 1; }
|
||||||
|
cat reports/secrets.txt reports/pip-audit.txt
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Select release') {
|
||||||
|
agent { label 'delivery' }
|
||||||
|
when { allOf { branch 'main'; expression { !params.RELEASE_RECORD } } }
|
||||||
|
steps {
|
||||||
|
script {
|
||||||
|
env.DELIVER = sh(returnStatus: true, script: 'git diff --quiet HEAD^1 HEAD -- pricing ansible Jenkinsfile') != 0 ? 'true' : 'false'
|
||||||
|
echo "pricing/, ansible/ or Jenkinsfile changed: ${env.DELIVER}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Build image') {
|
||||||
|
agent { label 'delivery' }
|
||||||
|
when { environment name: 'DELIVER', value: 'true' }
|
||||||
|
steps {
|
||||||
|
sh 'DOCKER_BUILDKIT=0 docker build --build-arg APP_COMMIT="$RELEASE_COMMIT" -t "$IMAGE:$RELEASE_COMMIT" pricing'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Scan image') {
|
||||||
|
agent { label 'delivery' }
|
||||||
|
when { environment name: 'DELIVER', value: 'true' }
|
||||||
|
steps {
|
||||||
|
sh '''
|
||||||
|
trivy image --image-src docker --scanners vuln --severity HIGH,CRITICAL \
|
||||||
|
--exit-code 1 --no-progress --output reports/image.txt "$IMAGE:$RELEASE_COMMIT" \
|
||||||
|
|| { cat reports/image.txt; exit 1; }
|
||||||
|
cat reports/image.txt
|
||||||
|
trivy version | tee reports/trivy-version.txt
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Publish image') {
|
||||||
|
agent { label 'delivery' }
|
||||||
|
when { environment name: 'DELIVER', value: 'true' }
|
||||||
|
steps {
|
||||||
|
withCredentials([usernamePassword(credentialsId: 'registry-write', usernameVariable: 'REG_USER', passwordVariable: 'REG_TOKEN')]) {
|
||||||
|
sh '''#!/bin/bash
|
||||||
|
set -euo pipefail
|
||||||
|
mkdir -p releases reports
|
||||||
|
export DOCKER_CONFIG=$(mktemp -d)
|
||||||
|
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
|
||||||
|
printf '%s' "$REG_TOKEN" | docker login "${IMAGE%%/*}" -u "$REG_USER" --password-stdin
|
||||||
|
docker push "$IMAGE:$RELEASE_COMMIT"
|
||||||
|
docker pull "$IMAGE:$RELEASE_COMMIT"
|
||||||
|
DIGEST=$(docker image inspect "$IMAGE:$RELEASE_COMMIT" --format '{{index .RepoDigests 0}}')
|
||||||
|
VERSION=$(sed -n 's/^VERSION = "\\(.*\\)"/\\1/p' pricing/app.py)
|
||||||
|
UNIT=$(sed -n 's/^UNIT_PRICE = //p' pricing/app.py)
|
||||||
|
for TARGET in staging production; do
|
||||||
|
HOST=app; [ "$TARGET" = staging ] && HOST=staging
|
||||||
|
cat > "releases/$VERSION-$TARGET.yml" <<EOF
|
||||||
|
target_env: $TARGET
|
||||||
|
release_image: $DIGEST
|
||||||
|
expected_version: $VERSION
|
||||||
|
expected_commit: $RELEASE_COMMIT
|
||||||
|
expected_total: $((UNIT * 3))
|
||||||
|
public_url: https://$HOST.pollefeys.dev
|
||||||
|
proxy_network: gitea_gitea-net
|
||||||
|
EOF
|
||||||
|
done
|
||||||
|
echo "$VERSION" > reports/version.txt
|
||||||
|
cat "releases/$VERSION-staging.yml"
|
||||||
|
'''
|
||||||
|
}
|
||||||
|
stash name: 'release', includes: 'releases/*.yml,reports/version.txt'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Deploy staging') {
|
||||||
|
agent { label 'delivery' }
|
||||||
|
when { environment name: 'DELIVER', value: 'true' }
|
||||||
|
steps {
|
||||||
|
unstash 'release'
|
||||||
|
script {
|
||||||
|
def version = readFile('reports/version.txt').trim()
|
||||||
|
deploy("releases/${version}-staging.yml", 'staging-first-run')
|
||||||
|
// An unchanged rerun must report no changes.
|
||||||
|
deploy("releases/${version}-staging.yml", 'staging-second-run')
|
||||||
|
sh 'grep -E "changed=0 +unreachable=0 +failed=0" reports/staging-second-run.txt'
|
||||||
|
smoke("releases/${version}-staging.yml")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Redeploy selected record') {
|
||||||
|
agent { label 'delivery' }
|
||||||
|
when { expression { params.RELEASE_RECORD && !params.RELEASE_RECORD.contains('production') } }
|
||||||
|
steps {
|
||||||
|
checkout scm
|
||||||
|
sh '''
|
||||||
|
if [ -n "$CONFIG_REF" ]; then
|
||||||
|
git fetch --quiet "$(git remote get-url origin)" '+refs/heads/*:refs/remotes/all/*'
|
||||||
|
git checkout "$CONFIG_REF" -- ansible
|
||||||
|
fi
|
||||||
|
'''
|
||||||
|
script {
|
||||||
|
deploy(params.RELEASE_RECORD, 'redeploy')
|
||||||
|
smoke(params.RELEASE_RECORD)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Production approval') {
|
||||||
|
when {
|
||||||
|
anyOf {
|
||||||
|
environment name: 'DELIVER', value: 'true'
|
||||||
|
expression { params.RELEASE_RECORD?.contains('production') }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
steps {
|
||||||
|
script {
|
||||||
|
def target = params.RELEASE_RECORD ?: 'the release built by this run'
|
||||||
|
timeout(time: 30, unit: 'MINUTES') {
|
||||||
|
env.APPROVER = input(
|
||||||
|
message: "Deploy ${target} to production? Commit ${env.RELEASE_COMMIT ?: 'see record'}, build ${env.BUILD_NUMBER}. Check the image digest, scan result, and staging result in this run first.",
|
||||||
|
ok: 'Approve production',
|
||||||
|
submitter: 'natalie,cedric',
|
||||||
|
submitterParameter: 'APPROVER'
|
||||||
|
)
|
||||||
|
}
|
||||||
|
echo "Approved by ${env.APPROVER}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Deploy production') {
|
||||||
|
agent { label 'delivery' }
|
||||||
|
when {
|
||||||
|
anyOf {
|
||||||
|
environment name: 'DELIVER', value: 'true'
|
||||||
|
expression { params.RELEASE_RECORD?.contains('production') }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
steps {
|
||||||
|
script {
|
||||||
|
def record = params.RELEASE_RECORD
|
||||||
|
if (record) {
|
||||||
|
checkout scm
|
||||||
|
// Production uses only reviewed configuration from main.
|
||||||
|
sh '''
|
||||||
|
if [ -n "$CONFIG_REF" ]; then
|
||||||
|
git merge-base --is-ancestor "$CONFIG_REF" HEAD
|
||||||
|
git checkout "$CONFIG_REF" -- ansible
|
||||||
|
fi
|
||||||
|
'''
|
||||||
|
} else {
|
||||||
|
unstash 'release'
|
||||||
|
record = "releases/${readFile('reports/version.txt').trim()}-production.yml"
|
||||||
|
}
|
||||||
|
withEnv(["RECORD=${record}"]) {
|
||||||
|
sh 'mkdir -p reports; echo "approver=$APPROVER time=$(date -u +%FT%TZ) record=$RECORD" | tee reports/approval.txt'
|
||||||
|
}
|
||||||
|
deploy(record, 'production')
|
||||||
|
smoke(record)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
post {
|
||||||
|
always {
|
||||||
|
node('delivery') {
|
||||||
|
archiveArtifacts artifacts: 'reports/**,releases/*.yml', allowEmptyArchive: true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
- name: Deploy a selected immutable pricing release
|
||||||
|
hosts: delivery
|
||||||
|
become: true
|
||||||
|
vars:
|
||||||
|
project_dir: "/opt/startup/pricing-{{ target_env }}"
|
||||||
|
tasks:
|
||||||
|
- name: Validate release selection
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that:
|
||||||
|
- target_env in ['staging', 'production']
|
||||||
|
- "'@sha256:' in release_image"
|
||||||
|
- expected_version in ['v1', 'v2']
|
||||||
|
- expected_total | int > 0
|
||||||
|
- public_url.startswith('https://')
|
||||||
|
- proxy_network | length > 0
|
||||||
|
- name: Create deployment directory
|
||||||
|
ansible.builtin.file:
|
||||||
|
path: "{{ project_dir }}"
|
||||||
|
state: directory
|
||||||
|
mode: '0750'
|
||||||
|
- name: Render selected Compose configuration
|
||||||
|
ansible.builtin.template:
|
||||||
|
src: compose.yaml.j2
|
||||||
|
dest: "{{ project_dir }}/compose.yaml"
|
||||||
|
mode: '0640'
|
||||||
|
- name: Converge application without rebuilding
|
||||||
|
community.docker.docker_compose_v2:
|
||||||
|
project_src: "{{ project_dir }}"
|
||||||
|
project_name: "pricing-{{ target_env }}"
|
||||||
|
state: present
|
||||||
|
build: never
|
||||||
|
pull: missing
|
||||||
|
wait: true
|
||||||
|
wait_timeout: 90
|
||||||
|
- name: Verify health through public TLS endpoint
|
||||||
|
ansible.builtin.uri:
|
||||||
|
url: "{{ public_url }}/health"
|
||||||
|
return_content: true
|
||||||
|
validate_certs: true
|
||||||
|
register: health
|
||||||
|
until: health.status == 200 and health.json.status == 'ok'
|
||||||
|
retries: 12
|
||||||
|
delay: 5
|
||||||
|
changed_when: false
|
||||||
|
- name: Read release identity
|
||||||
|
ansible.builtin.uri:
|
||||||
|
url: "{{ public_url }}/"
|
||||||
|
return_content: true
|
||||||
|
register: identity
|
||||||
|
changed_when: false
|
||||||
|
- name: Exercise business behavior
|
||||||
|
ansible.builtin.uri:
|
||||||
|
url: "{{ public_url }}/price?quantity=3"
|
||||||
|
return_content: true
|
||||||
|
register: price
|
||||||
|
changed_when: false
|
||||||
|
- name: Check release identity and calculation
|
||||||
|
ansible.builtin.assert:
|
||||||
|
that:
|
||||||
|
- identity.json.version == expected_version
|
||||||
|
- identity.json.commit == expected_commit
|
||||||
|
- price.json.total | int == expected_total | int
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
[delivery]
|
||||||
|
# 172.18.0.1 is the droplet host as seen from the delivery agent on gitea_gitea-net.
|
||||||
|
startup ansible_host=172.18.0.1 ansible_user=deploy ansible_ssh_common_args='-o UserKnownHostsFile=ansible/known_hosts -o StrictHostKeyChecking=yes'
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
172.18.0.1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPvkyH0+3FOyLD81nBpbyYomdRhwEUhEnrRLfp7/UQPV
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Copy to a release-specific file and replace EVERY placeholder.
|
||||||
|
target_env: staging
|
||||||
|
release_image: git.pollefeys.dev/seatbacktrivia/pricing@sha256:REPLACE_DIGEST
|
||||||
|
expected_version: v1
|
||||||
|
expected_commit: REPLACE_FULL_GIT_COMMIT
|
||||||
|
expected_total: 30
|
||||||
|
public_url: https://staging.pollefeys.dev
|
||||||
|
proxy_network: gitea_gitea-net
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
collections:
|
||||||
|
- name: community.docker
|
||||||
|
version: ">=4.8.0,<6.0.0"
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
services:
|
||||||
|
app:
|
||||||
|
image: "{{ release_image }}"
|
||||||
|
restart: unless-stopped
|
||||||
|
read_only: true
|
||||||
|
tmpfs:
|
||||||
|
- /tmp
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
networks:
|
||||||
|
edge:
|
||||||
|
aliases:
|
||||||
|
- "pricing-{{ target_env }}"
|
||||||
|
networks:
|
||||||
|
edge:
|
||||||
|
external: true
|
||||||
|
name: "{{ proxy_network }}"
|
||||||
@@ -10,3 +10,10 @@ ci.pollefeys.dev {
|
|||||||
metrics.pollefeys.dev {
|
metrics.pollefeys.dev {
|
||||||
reverse_proxy grafana:3000
|
reverse_proxy grafana:3000
|
||||||
}
|
}
|
||||||
|
# Pricing service: one Compose project per environment, joined to gitea_gitea-net.
|
||||||
|
staging.pollefeys.dev {
|
||||||
|
reverse_proxy pricing-staging:8000
|
||||||
|
}
|
||||||
|
app.pollefeys.dev {
|
||||||
|
reverse_proxy pricing-production:8000
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Trusted delivery agent: Docker CLI, Ansible, Trivy, and pip-audit. All tools are
|
||||||
|
# in the image, so recreating the container loses nothing.
|
||||||
|
FROM jenkins/inbound-agent:3395.v6e5377b_0fb_3c-3-jdk21
|
||||||
|
USER root
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends python3 python3-venv openssh-client curl ca-certificates && rm -rf /var/lib/apt/lists/* && curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-29.8.1.tgz | tar xz --strip-components=1 -C /usr/local/bin docker/docker && curl -fsSLo /tmp/trivy.tgz https://github.com/aquasecurity/trivy/releases/download/v0.75.0/trivy_0.75.0_Linux-64bit.tar.gz && echo "c6e65abddb348e25f10549df887045629cf28cc72453cd1c63acb717316b3f3f /tmp/trivy.tgz" | sha256sum -c - && tar xzf /tmp/trivy.tgz -C /usr/local/bin trivy && rm /tmp/trivy.tgz && python3 -m venv /opt/delivery && /opt/delivery/bin/pip install --no-cache-dir ansible-core==2.22.0 pip-audit==2.10.1
|
||||||
|
USER jenkins
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Inbound Jenkins agent for the delivery stages. The Docker socket makes this
|
||||||
|
# container equivalent to host root, so only reviewed main-branch stages use its
|
||||||
|
# credentials. DOCKER_GID and JENKINS_SECRET come from an untracked .env file.
|
||||||
|
name: jenkins-agent
|
||||||
|
|
||||||
|
services:
|
||||||
|
agent:
|
||||||
|
build: .
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
- JENKINS_URL=http://jenkins:8080
|
||||||
|
- JENKINS_AGENT_NAME=delivery-agent
|
||||||
|
- JENKINS_SECRET=${JENKINS_SECRET}
|
||||||
|
- JENKINS_WEB_SOCKET=true
|
||||||
|
- JAVA_OPTS=-Xmx96m
|
||||||
|
group_add:
|
||||||
|
- "${DOCKER_GID}"
|
||||||
|
volumes:
|
||||||
|
- agent-data:/home/jenkins/agent
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
networks:
|
||||||
|
- gitea-net
|
||||||
|
logging:
|
||||||
|
options:
|
||||||
|
max-size: 10m
|
||||||
|
max-file: "3"
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
agent-data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
gitea-net:
|
||||||
|
external: true
|
||||||
|
name: gitea_gitea-net
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
__pycache__
|
||||||
|
.venv
|
||||||
|
.git
|
||||||
|
*.pyc
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
FROM python:3.13-alpine3.23@sha256:e4aeaca9081549f19bd5bc8605ed5ab257ba34f97e0471f8e09161f45b4b08b8
|
||||||
|
ARG APP_COMMIT=development
|
||||||
|
ENV APP_COMMIT=$APP_COMMIT PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt .
|
||||||
|
# pip is not needed at runtime, and its bundled packages carry scanner findings.
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt && python -m pip uninstall -y pip && rm -rf /usr/local/lib/python3.13/ensurepip
|
||||||
|
COPY app.py .
|
||||||
|
USER 10001:10001
|
||||||
|
EXPOSE 8000
|
||||||
|
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2)"
|
||||||
|
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "1", "--worker-tmp-dir", "/tmp", "app:app"]
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import os
|
||||||
|
from flask import Flask, jsonify, request
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
VERSION = "v1"
|
||||||
|
UNIT_PRICE = 10
|
||||||
|
COMMIT = os.environ.get("APP_COMMIT", "development")
|
||||||
|
|
||||||
|
|
||||||
|
def total_price(quantity):
|
||||||
|
if quantity < 1 or quantity > 1000:
|
||||||
|
raise ValueError("quantity must be between 1 and 1000")
|
||||||
|
return UNIT_PRICE * quantity
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/")
|
||||||
|
def index():
|
||||||
|
return jsonify(service="Startup Pricing", version=VERSION, commit=COMMIT)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health():
|
||||||
|
return jsonify(status="ok", version=VERSION)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/price")
|
||||||
|
def price():
|
||||||
|
try:
|
||||||
|
quantity = int(request.args.get("quantity", "1"))
|
||||||
|
total = total_price(quantity)
|
||||||
|
except ValueError as error:
|
||||||
|
return jsonify(error=str(error)), 400
|
||||||
|
return jsonify(quantity=quantity, total=total, currency="USD")
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
blinker==1.9.0
|
||||||
|
click==8.5.0
|
||||||
|
Flask==3.1.3
|
||||||
|
gunicorn==23.0.0
|
||||||
|
itsdangerous==2.2.0
|
||||||
|
Jinja2==3.1.6
|
||||||
|
MarkupSafe==3.0.4
|
||||||
|
packaging==26.3
|
||||||
|
Werkzeug==3.1.9
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import unittest
|
||||||
|
from app import app, total_price
|
||||||
|
|
||||||
|
|
||||||
|
class PricingTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.client = app.test_client()
|
||||||
|
|
||||||
|
def test_price(self):
|
||||||
|
self.assertEqual(total_price(3), 30)
|
||||||
|
response = self.client.get("/price?quantity=3")
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(response.json["total"], 30)
|
||||||
|
|
||||||
|
def test_invalid_quantity(self):
|
||||||
|
for value in ["0", "-1", "1001", "abc", "1.5"]:
|
||||||
|
self.assertEqual(self.client.get("/price?quantity=" + value).status_code, 400)
|
||||||
|
|
||||||
|
def test_release_identity(self):
|
||||||
|
self.assertEqual(self.client.get("/").json["version"], "v1")
|
||||||
|
self.assertEqual(self.client.get("/health").json["status"], "ok")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user