Move CI runners to Droplet and enable application HTTPS
vpn-dns-gateway/pipeline/pr-main This commit looks good
vpn-dns-gateway/pipeline/pr-main This commit looks good
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
#!/bin/sh
|
||||
# Run inside the idle trusted agent from a non-secret preparation snapshot.
|
||||
# This is a capacity/tool trial, never a reviewed release or registry push.
|
||||
set -eu
|
||||
export TRIVY_CACHE_DIR=/home/jenkins/agent/.cache/trivy
|
||||
mkdir -p build/delivery/reports
|
||||
date -u
|
||||
python3 -B -m unittest discover -s delivery/ci -p 'test_controls.py' -v
|
||||
sh delivery/ci/test-app.sh
|
||||
python3 delivery/ci/security.py source
|
||||
: "${DELIVERY_BUILDER:?use the limited remote builder}"
|
||||
docker buildx build --builder "$DELIVERY_BUILDER" --load --platform linux/amd64 \
|
||||
--build-arg APP_COMMIT=uncommitted-remote-preflight \
|
||||
-t ssw590-pricing:remote-preflight-v1 delivery/app
|
||||
python3 delivery/ci/security.py image --image ssw590-pricing:remote-preflight-v1
|
||||
name=ssw590-delivery-capacity-smoke
|
||||
cleanup() { docker rm -f "$name" >/dev/null 2>&1 || true; }
|
||||
# Refuse to replace any existing container, even one from an interrupted trial.
|
||||
if docker container inspect "$name" >/dev/null 2>&1; then
|
||||
echo 'Inspect the existing trial container before retrying' >&2
|
||||
exit 1
|
||||
fi
|
||||
trap cleanup EXIT
|
||||
docker run -d --name "$name" --network gitea_web --read-only \
|
||||
--tmpfs /tmp:rw,nosuid,noexec,size=16m --memory 64m --memory-swap 96m \
|
||||
--cpus .25 --pids-limit 64 --cap-drop ALL --security-opt no-new-privileges \
|
||||
ssw590-pricing:remote-preflight-v1
|
||||
python3 - <<'PY'
|
||||
import json, time, urllib.request, urllib.error
|
||||
url = 'http://ssw590-delivery-capacity-smoke:8000'
|
||||
for attempt in range(30):
|
||||
try:
|
||||
with urllib.request.urlopen(url + '/health', timeout=2) as response:
|
||||
health = json.load(response)
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise RuntimeError('Application failed to start')
|
||||
def get(path):
|
||||
with urllib.request.urlopen(url + path, timeout=5) as response:
|
||||
return json.load(response)
|
||||
identity, price = get('/'), get('/price?quantity=3')
|
||||
assert health['status'] == 'ok' and health['version'] == 'v1', health
|
||||
assert identity['commit'] == 'uncommitted-remote-preflight', identity
|
||||
assert price['total'] == 30, price
|
||||
try:
|
||||
get('/price?quantity=-1')
|
||||
raise AssertionError('Invalid quantity accepted')
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 400, error.code
|
||||
print(json.dumps({'health': health, 'identity': identity, 'price': price,
|
||||
'invalid_quantity_status': 400}, indent=2))
|
||||
PY
|
||||
docker inspect "$name" --format 'smoke OOMKilled={{.State.OOMKilled}} memory={{.HostConfig.Memory}}'
|
||||
date -u
|
||||
echo 'PASS: remote capacity preparation; no image published or assessed environment deployed'
|
||||
@@ -46,7 +46,7 @@ def knownHosts = new FileCredentialsImpl(scope, 'delivery-known-hosts',
|
||||
assert store.addCredentials(Domain.global(), knownHosts)
|
||||
def launcher = new JNLPLauncher()
|
||||
launcher.setWebSocket(true)
|
||||
def node = new DumbSlave('ssw590-vince-delivery', 'Trusted laptop Docker/Ansible delivery agent',
|
||||
def node = new DumbSlave('ssw590-vince-delivery', 'Trusted The-Ocean Docker/Ansible delivery agent (legacy node name)',
|
||||
'/home/jenkins/agent', '1', Node.Mode.EXCLUSIVE, 'delivery-trusted', launcher,
|
||||
new RetentionStrategy.Always(), [])
|
||||
j.addNode(node)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Apply only the prepared Assignment 8 proxy additions, preserving the bind inode."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--candidate', required=True, type=Path)
|
||||
parser.add_argument('--backup', required=True, type=Path)
|
||||
parser.add_argument('--apply', action='store_true')
|
||||
args = parser.parse_args()
|
||||
live = Path('/root/gitea/Caddyfile')
|
||||
marker = '# Assignment 8: apply after both DNS names resolve to The-Ocean.'
|
||||
candidate = args.candidate.read_text()
|
||||
before = live.read_bytes()
|
||||
prefix, additions = candidate.split(marker, 1)
|
||||
expected = '''# Assignment 8: apply after both DNS names resolve to The-Ocean. Containers
|
||||
# publish no host ports; the existing proxy reaches their private aliases.
|
||||
staging.yebilly.me {
|
||||
\treverse_proxy pricing-staging:8000
|
||||
}
|
||||
|
||||
app.yebilly.me {
|
||||
\treverse_proxy pricing-production:8000
|
||||
}'''
|
||||
assert (marker + additions).strip() == expected, 'Unexpected proxy additions'
|
||||
assert prefix.strip() == before.decode().replace('\r\n', '\n').strip(), 'Live earlier routes differ; inspect instead of overwriting'
|
||||
for host in ('staging.yebilly.me', 'app.yebilly.me'):
|
||||
addresses = {item[4][0] for item in socket.getaddrinfo(host, 443, socket.AF_INET)}
|
||||
assert addresses == {'147.182.178.136'}, (host, addresses)
|
||||
temp = '/tmp/ssw590-assignment8-https.Caddyfile'
|
||||
subprocess.run(['docker', 'cp', str(args.candidate), 'gitea-caddy-1:' + temp], check=True)
|
||||
try:
|
||||
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'caddy', 'validate', '--config', temp, '--adapter', 'caddyfile'], check=True)
|
||||
if not args.apply:
|
||||
print('Candidate validated; no active configuration changed.')
|
||||
raise SystemExit(0)
|
||||
args.backup.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
backup = args.backup / 'Caddyfile.before'
|
||||
assert not backup.exists(), 'Existing backup: inspect state before retrying'
|
||||
shutil.copy2(live, backup)
|
||||
prior_stat = live.stat()
|
||||
try:
|
||||
with live.open('wb') as stream:
|
||||
stream.write(candidate.encode())
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
assert live.stat().st_ino == prior_stat.st_ino, 'Bind-mounted inode changed'
|
||||
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'caddy', 'reload', '--config', '/etc/caddy/Caddyfile', '--adapter', 'caddyfile'], check=True)
|
||||
except Exception:
|
||||
with live.open('wb') as stream:
|
||||
stream.write(before)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'caddy', 'reload', '--config', '/etc/caddy/Caddyfile', '--adapter', 'caddyfile'], check=True)
|
||||
raise
|
||||
report = {'applied_at': datetime.now(timezone.utc).isoformat(),
|
||||
'before_sha256': hashlib.sha256(before).hexdigest(),
|
||||
'after_sha256': hashlib.sha256(live.read_bytes()).hexdigest(),
|
||||
'inode_preserved': live.stat().st_ino == prior_stat.st_ino,
|
||||
'prior_routes_preserved': True, 'applications_deployed': False,
|
||||
'new_hosts': ['staging.yebilly.me', 'app.yebilly.me'],
|
||||
'backup': str(backup), 'result': 'reloaded; certificate verification pending'}
|
||||
(args.backup / 'applied.json').write_text(json.dumps(report, indent=2))
|
||||
print(json.dumps(report, indent=2))
|
||||
finally:
|
||||
subprocess.run(['docker', 'exec', 'gitea-caddy-1', 'rm', '-f', temp], check=True)
|
||||
@@ -1,9 +1,13 @@
|
||||
param(
|
||||
[switch]$AllowLaptopFallback,
|
||||
[string]$Droplet = '147.182.178.136',
|
||||
[string]$IdentityFile = (Join-Path $env:USERPROFILE '.ssh/digitalocean')
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$PSNativeCommandUseErrorActionPreference = $true
|
||||
if (-not $AllowLaptopFallback) {
|
||||
throw 'The delivery node now runs on The-Ocean. Start a laptop fallback only after stopping the remote copy, then pass -AllowLaptopFallback. Never connect both copies of the same node.'
|
||||
}
|
||||
$repoPath = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
|
||||
$sshArguments = @('-i', $IdentityFile, '-o', 'IdentitiesOnly=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=10', "root@$Droplet")
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
# Run as root from /opt/ssw590-delivery-agent after stopping the laptop copy.
|
||||
# Copy compose.droplet.yaml and ssh_config.droplet here first; load the verified
|
||||
# agent image. Never copy any identity file into this directory or into Git.
|
||||
set -euo pipefail
|
||||
test "$(id -u)" = 0
|
||||
cd /opt/ssw590-delivery-agent
|
||||
export DOCKER_GID
|
||||
DOCKER_GID=$(stat -c '%g' /var/run/docker.sock)
|
||||
# Numeric group only, not a credential. Keep it available for later Compose use.
|
||||
printf 'DOCKER_GID=%s\n' "$DOCKER_GID" > .env
|
||||
chmod 644 .env
|
||||
docker image inspect ssw590-delivery-agent:20261114 >/dev/null
|
||||
docker compose -f compose.droplet.yaml config --quiet
|
||||
docker exec -u jenkins gitea-jenkins-1 test -s /var/jenkins_home/delivery-bootstrap/agent-secret
|
||||
docker volume create ssw590-delivery-identity >/dev/null
|
||||
docker exec -u jenkins gitea-jenkins-1 cat /var/jenkins_home/delivery-bootstrap/agent-secret |
|
||||
docker run --rm -i --network none --user 0:0 --entrypoint sh \
|
||||
--mount type=volume,source=ssw590-delivery-identity,target=/identity \
|
||||
ssw590-delivery-agent:20261114 -c \
|
||||
'set -eu; umask 077; cat > /identity/agent-secret; test -s /identity/agent-secret; chown 1000:1000 /identity /identity/agent-secret; chmod 700 /identity; chmod 400 /identity/agent-secret'
|
||||
docker compose -f compose.droplet.yaml up -d --pull never
|
||||
agent=ssw590-delivery-agent-1
|
||||
# BuildKit's own container must be limited too: the socket mount does not make
|
||||
# child build containers inherit the agent's resource caps.
|
||||
if ! docker exec "$agent" docker buildx inspect ssw590-delivery-limited >/dev/null 2>&1; then
|
||||
docker exec "$agent" docker buildx create --name ssw590-delivery-limited \
|
||||
--driver docker-container \
|
||||
--driver-opt image=moby/buildkit@sha256:c5f8862f52499773af85bc07695b2379ef08e8002352b0df2c4864c91d78dabe,memory=256m,memory-swap=384m,cpu-period=100000,cpu-quota=50000,restart-policy=unless-stopped
|
||||
fi
|
||||
docker exec "$agent" docker buildx inspect ssw590-delivery-limited --bootstrap
|
||||
docker compose -f compose.droplet.yaml ps
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Read-only, non-secret runtime checks; run as root on The-Ocean."""
|
||||
import json
|
||||
import subprocess
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def run(*args):
|
||||
return subprocess.check_output(args, text=True).strip()
|
||||
|
||||
|
||||
report = {"observed_at": datetime.now(timezone.utc).isoformat(), "containers": []}
|
||||
names = ["ssw590-delivery-agent-1", "buildx_buildkit_ssw590-delivery-limited0"]
|
||||
for name in names:
|
||||
info = json.loads(run("docker", "inspect", name))[0]
|
||||
config, state = info["HostConfig"], info["State"]
|
||||
events = Path("/sys/fs/cgroup/system.slice", "docker-" + info["Id"] + ".scope", "memory.events")
|
||||
report["containers"].append({
|
||||
"name": name, "running": state["Running"], "oom_killed": state["OOMKilled"],
|
||||
"restart_count": info["RestartCount"], "restart_policy": config["RestartPolicy"]["Name"],
|
||||
"memory_bytes": config["Memory"], "memory_swap_bytes": config["MemorySwap"],
|
||||
"nano_cpus": config["NanoCpus"], "cpu_quota": config["CpuQuota"],
|
||||
"cpu_period": config["CpuPeriod"], "port_bindings": config["PortBindings"],
|
||||
"memory_events": events.read_text().strip() if events.exists() else "unavailable",
|
||||
})
|
||||
assert state["Running"] and not state["OOMKilled"], name
|
||||
report["private_http"] = {}
|
||||
for url in ["http://jenkins:8080/login", "http://gitea:3000/", "http://monitoring-grafana-1:3000/login"]:
|
||||
code = run("docker", "exec", names[0], "curl", "--silent", "--show-error", "--max-time", "15",
|
||||
"-o", "/dev/null", "-w", "%{http_code}", url)
|
||||
report["private_http"][url] = code
|
||||
assert code == "200", (url, code)
|
||||
ssh = run("docker", "exec", names[0], "ssh", "-G", "147.182.178.136")
|
||||
report["deployment_ssh_route"] = [line for line in ssh.splitlines() if line.startswith(("hostname ", "hostkeyalias "))]
|
||||
assert "hostname host.docker.internal" in ssh.splitlines()
|
||||
assert "hostkeyalias 147.182.178.136" in ssh.splitlines()
|
||||
report["memory"] = run("free", "-m")
|
||||
report["disk"] = run("df", "-h", "/")
|
||||
report["running_containers"] = run("docker", "ps", "--format", "{{.Names}} {{.Status}}")
|
||||
report["result"] = "passed"
|
||||
print(json.dumps(report, indent=2))
|
||||
Reference in New Issue
Block a user