Завершить уровень 4: проверить ошибки, ограничить память и автоматизировать сверку S3

This commit is contained in:
2026-10-30 17:47:29 +03:00
parent 4f85fb96a6
commit 9dded977a5
25 changed files with 1213 additions and 90 deletions
+24
View File
@@ -0,0 +1,24 @@
name: Application lab4
on: [push, pull_request]
permissions:
contents: read
jobs:
application:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: python scripts/bootstrap.py
- run: docker compose build api s3
- run: docker compose up -d
- run: python scripts/wait_ready.py --base-url http://localhost:8084 --replicas 2
- run: make check test PYTHON=python BASE_URL=http://localhost:8084
- run: docker compose run --rm --no-deps -T -v "$PWD:/suite:ro" -w /suite api python student-tests/test_attachments.py
- run: docker compose run --rm --no-deps -T -v "$PWD:/suite:ro" -w /suite api python student-tests/test_reconcile.py
- run: chmod +x scripts/restart.sh scripts/stop-one.sh
- run: make test-persistence PYTHON=python BASE_URL=http://localhost:8084 ACTION_SCRIPT=scripts/restart.sh
- if: always()
run: docker compose down
+1 -1
View File
@@ -1,4 +1,4 @@
FROM python:3.11.10-slim-bookworm
FROM python:3.11.10-slim-bookworm@sha256:840e180ebcc6e5c8efab209c43f5e40fd2af98cb49db5c7103c90539c56bb30e
WORKDIR /app
# Приложение работает без прав root.
RUN groupadd -r appuser && useradd -r -g appuser appuser
+17
View File
@@ -0,0 +1,17 @@
# Reproducible fallback: official MinIO images are unavailable from registries.
FROM golang:1.24.6-bookworm@sha256:ab1d1823abb55a9504d2e3e003b75b36dbeb1cbcc4c92593d85a84ee46becc6c AS build
WORKDIR /build
ADD --checksum=sha256:8819e3e7817e46b7b3798f8f200ead208562e571563c2e040352378031abe9f2 https://github.com/minio/minio/archive/07c3a429bfed433e49018cb0f78a52145d4bedeb.tar.gz /tmp/minio.tar.gz
RUN tar -xzf /tmp/minio.tar.gz --strip-components=1 && CGO_ENABLED=0 go build -trimpath -o /out/minio .
WORKDIR /build-mc
ADD --checksum=sha256:526ec538e7f83e4bfa631788129b08ec85898ca572ce0523ebf9a597946bea27 https://github.com/minio/mc/archive/refs/tags/RELEASE.2025-04-16T18-13-26Z.tar.gz /tmp/mc.tar.gz
RUN tar -xzf /tmp/mc.tar.gz --strip-components=1 && CGO_ENABLED=0 go build -trimpath -o /out/mc .
FROM debian:bookworm-20251020-slim@sha256:78d2f66e0fec9e5a39fb2c72ea5e052b548df75602b5215ed01a17171529f706
LABEL org.opencontainers.image.source="https://github.com/minio/minio" org.opencontainers.image.revision="07c3a429bfed433e49018cb0f78a52145d4bedeb"
COPY --from=build /build/LICENSE /usr/share/doc/minio/LICENSE
COPY --from=build /build-mc/LICENSE /usr/share/doc/mc/LICENSE
COPY --from=build /out/minio /out/mc /usr/bin/
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY infra/s3-entrypoint.sh /usr/local/bin/s3-entrypoint.sh
ENTRYPOINT ["/bin/sh","/usr/local/bin/s3-entrypoint.sh"]
CMD ["server","/data"]
+19 -2
View File
@@ -49,7 +49,10 @@ services:
healthcheck:
disable: true
s3:
image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e
image: lyakhonov-storage:lab4
build:
context: .
dockerfile: Dockerfile.s3
command: [server, /data, --console-address, '127.0.0.1:9001']
environment:
MINIO_ROOT_USER_FILE: /run/secrets/s3_root_user
@@ -59,7 +62,8 @@ services:
cpus: 1
mem_limit: 768m
bucket-init:
image: minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e
image: lyakhonov-storage:lab4
pull_policy: never
entrypoint: [/bin/sh, /bootstrap/bucket.sh]
secrets: [s3_root_user, s3_root_password, s3_access_key, s3_secret_key]
volumes: [./infra/bucket.sh:/bootstrap/bucket.sh:ro, ./infra/s3-policy.json:/bootstrap/policy.json:ro]
@@ -73,6 +77,19 @@ services:
condition: service_completed_successfully
deploy:
replicas: ${API_REPLICAS:-2}
reconciler:
<<: *api
command: [python, -m, src.reconcile, --apply, --interval, '300']
restart: unless-stopped
cpus: 0.25
mem_limit: 256m
healthcheck:
disable: true
depends_on:
migrate:
condition: service_completed_successfully
bucket-init:
condition: service_completed_successfully
lb:
image: haproxy:3.0.6-alpine
ports: ["127.0.0.1:${LAB4_PORT:-8084}:8080"]
+1
View File
@@ -0,0 +1 @@
{"result": "PASS", "concurrent_retries": 16, "failure_after_s3_put": true, "interrupted_upload_no_object": true, "private_bucket": true, "restricted_credentials": true}
+1
View File
@@ -0,0 +1 @@
Private bucket and restricted application user ready
+5
View File
@@ -0,0 +1,5 @@
{
"Name": "13th Gen Intel(R) Core(TM) i5-1340P",
"NumberOfCores": 12,
"NumberOfLogicalProcessors": 16
}
+8
View File
@@ -0,0 +1,8 @@
{
"ServerVersion": "28.5.1",
"NCPU": 16,
"MemTotal": 8126664704,
"OSType": "linux",
"OperatingSystem": "Docker Desktop",
"Architecture": "x86_64"
}
+4
View File
@@ -0,0 +1,4 @@
{
"NumberOfLogicalProcessors": 16,
"TotalPhysicalMemory": 16778182656
}
+44
View File
@@ -0,0 +1,44 @@
{
"negative_suite": {
"result": "PASS",
"concurrent_retries": 16,
"failure_after_s3_put": true,
"interrupted_upload_no_object": true,
"private_bucket": true,
"restricted_credentials": true
},
"uploads": [
{
"size_bytes": 3151219,
"successful_rps_median": 16.729828936800814,
"p50_seconds_median": 0.4081998335022945,
"p95_seconds_median": 0.584588757907477,
"p99_seconds_median": 0.5914236595887633,
"errors": 0,
"attempts": 30,
"elapsed_seconds": 1.8537453600001754
},
{
"size_bytes": 9648062,
"successful_rps_median": 5.626450903085569,
"p50_seconds_median": 1.0610903210035758,
"p95_seconds_median": 1.7164175714497103,
"p99_seconds_median": 1.7635092142925715,
"errors": 0,
"attempts": 30,
"elapsed_seconds": 5.111771299998509
}
],
"kernel_memory_peak_mib": {
"68ab8db39c84": 167.9453125,
"a6106479affd": 156.98046875
},
"sampled_memory_max_mib": {
"lyakhonov-lab4-api-1": 157.2,
"lyakhonov-lab4-api-2": 149.2,
"lyakhonov-lab4-db-1": 40.3,
"lyakhonov-lab4-lb-1": 17.27,
"lyakhonov-lab4-s3-1": 312.1
},
"cleanup_mechanism": "src.reconcile, grace 3600 seconds, interval 300 seconds; explicit 5-second synthetic test in track evidence"
}
+4
View File
@@ -0,0 +1,4 @@
python scripts/check_contract.py
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
python tests/smoke.py --base-url "http://localhost:8084"
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
+86 -86
View File
@@ -3,124 +3,64 @@
"each_uploading_replica_stopped": [
{
"stopped": {
"id": "24498cc4891a",
"hostname": "24498cc4891a",
"id": "550435eb1893",
"hostname": "550435eb1893",
"name": "lyakhonov-lab4-api-1",
"running": true,
"started_at": "2026-10-30T14:31:07.744742532Z",
"started_at": "2026-10-30T14:38:55.142398594Z",
"project": "lyakhonov-lab4"
},
"after": {
"id": "24498cc4891a",
"hostname": "24498cc4891a",
"id": "550435eb1893",
"hostname": "550435eb1893",
"name": "lyakhonov-lab4-api-1",
"running": false,
"started_at": "2026-10-30T14:31:07.744742532Z",
"started_at": "2026-10-30T14:38:55.142398594Z",
"project": "lyakhonov-lab4"
},
"download_instance": "950e5ae78851-f8e15971",
"download_instance": "5c0c5d76b6ee-fbcdf384",
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
"recovery_seconds": 1.135
"recovery_seconds": 1.286
},
{
"stopped": {
"id": "950e5ae78851",
"hostname": "950e5ae78851",
"id": "5c0c5d76b6ee",
"hostname": "5c0c5d76b6ee",
"name": "lyakhonov-lab4-api-2",
"running": true,
"started_at": "2026-10-30T14:31:12.431277515Z",
"started_at": "2026-10-30T14:38:54.95782885Z",
"project": "lyakhonov-lab4"
},
"after": {
"id": "950e5ae78851",
"hostname": "950e5ae78851",
"id": "5c0c5d76b6ee",
"hostname": "5c0c5d76b6ee",
"name": "lyakhonov-lab4-api-2",
"running": false,
"started_at": "2026-10-30T14:31:12.431277515Z",
"started_at": "2026-10-30T14:38:54.95782885Z",
"project": "lyakhonov-lab4"
},
"download_instance": "24498cc4891a-5564fcf3",
"download_instance": "550435eb1893-4bee0210",
"sha256": "99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75",
"recovery_seconds": 1.096
"recovery_seconds": 1.406
}
],
"s3_503_seconds": 4.046069000149146,
"s3_503_seconds": 4.043458599830046,
"restart_before": {
"api": [
{
"id": "24498cc4891a",
"hostname": "24498cc4891a",
"id": "550435eb1893",
"hostname": "550435eb1893",
"name": "lyakhonov-lab4-api-1",
"running": true,
"started_at": "2026-10-30T14:31:55.001303564Z",
"started_at": "2026-10-30T14:40:54.440796232Z",
"project": "lyakhonov-lab4"
},
{
"id": "950e5ae78851",
"hostname": "950e5ae78851",
"id": "5c0c5d76b6ee",
"hostname": "5c0c5d76b6ee",
"name": "lyakhonov-lab4-api-2",
"running": true,
"started_at": "2026-10-30T14:31:59.649868974Z",
"project": "lyakhonov-lab4"
}
],
"db": [
{
"id": "10138b5c0bee",
"hostname": "10138b5c0bee",
"name": "lyakhonov-lab4-db-1",
"running": true,
"started_at": "2026-10-30T14:30:00.149637002Z",
"project": "lyakhonov-lab4"
}
],
"redis": [
{
"id": "68997bbba33b",
"hostname": "68997bbba33b",
"name": "lyakhonov-lab4-redis-1",
"running": true,
"started_at": "2026-10-30T14:30:00.082955484Z",
"project": "lyakhonov-lab4"
}
],
"s3": [
{
"id": "83df7acfb73f",
"hostname": "83df7acfb73f",
"name": "lyakhonov-lab4-s3-1",
"running": true,
"started_at": "2026-10-30T14:32:07.860463524Z",
"project": "lyakhonov-lab4"
}
],
"lb": [
{
"id": "e9682a892ad3",
"hostname": "e9682a892ad3",
"name": "lyakhonov-lab4-lb-1",
"running": true,
"started_at": "2026-10-30T14:29:59.993685266Z",
"project": "lyakhonov-lab4"
}
]
},
"restart_after": {
"api": [
{
"id": "24498cc4891a",
"hostname": "24498cc4891a",
"name": "lyakhonov-lab4-api-1",
"running": true,
"started_at": "2026-10-30T14:32:12.97023467Z",
"project": "lyakhonov-lab4"
},
{
"id": "950e5ae78851",
"hostname": "950e5ae78851",
"name": "lyakhonov-lab4-api-2",
"running": true,
"started_at": "2026-10-30T14:32:13.834829902Z",
"started_at": "2026-10-30T14:40:59.474039309Z",
"project": "lyakhonov-lab4"
}
],
@@ -146,11 +86,11 @@
],
"s3": [
{
"id": "83df7acfb73f",
"hostname": "83df7acfb73f",
"id": "8d6296c66f50",
"hostname": "8d6296c66f50",
"name": "lyakhonov-lab4-s3-1",
"running": true,
"started_at": "2026-10-30T14:32:12.440778626Z",
"started_at": "2026-10-30T14:41:07.545035588Z",
"project": "lyakhonov-lab4"
}
],
@@ -164,5 +104,65 @@
"project": "lyakhonov-lab4"
}
]
},
"restart_after": {
"api": [
{
"id": "550435eb1893",
"hostname": "550435eb1893",
"name": "lyakhonov-lab4-api-1",
"running": true,
"started_at": "2026-10-30T14:41:12.906035738Z",
"project": "lyakhonov-lab4"
},
{
"id": "5c0c5d76b6ee",
"hostname": "5c0c5d76b6ee",
"name": "lyakhonov-lab4-api-2",
"running": true,
"started_at": "2026-10-30T14:41:12.736844839Z",
"project": "lyakhonov-lab4"
}
],
"db": [
{
"id": "10138b5c0bee",
"hostname": "10138b5c0bee",
"name": "lyakhonov-lab4-db-1",
"running": true,
"started_at": "2026-10-30T14:41:12.415067466Z",
"project": "lyakhonov-lab4"
}
],
"redis": [
{
"id": "68997bbba33b",
"hostname": "68997bbba33b",
"name": "lyakhonov-lab4-redis-1",
"running": true,
"started_at": "2026-10-30T14:41:12.598940634Z",
"project": "lyakhonov-lab4"
}
],
"s3": [
{
"id": "8d6296c66f50",
"hostname": "8d6296c66f50",
"name": "lyakhonov-lab4-s3-1",
"running": true,
"started_at": "2026-10-30T14:41:12.309884842Z",
"project": "lyakhonov-lab4"
}
],
"lb": [
{
"id": "e9682a892ad3",
"hostname": "e9682a892ad3",
"name": "lyakhonov-lab4-lb-1",
"running": true,
"started_at": "2026-10-30T14:41:12.504270669Z",
"project": "lyakhonov-lab4"
}
]
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"minio": {
"url": "https://github.com/minio/minio/archive/07c3a429bfed433e49018cb0f78a52145d4bedeb.tar.gz",
"sha256": "8819e3e7817e46b7b3798f8f200ead208562e571563c2e040352378031abe9f2"
},
"mc": {
"url": "https://github.com/minio/mc/archive/refs/tags/RELEASE.2025-04-16T18-13-26Z.tar.gz",
"sha256": "526ec538e7f83e4bfa631788129b08ec85898ca572ce0523ebf9a597946bea27"
}
}
+1
View File
@@ -0,0 +1 @@
{"result": "PASS", "profile": "closed-loop batch, 10 simultaneous uploads, 3 repeats per size, 1 warmup, all confirmed originals downloaded", "runs": [{"size_bytes": 3151219, "side": 1024, "repeat": 1, "concurrency": 10, "attempts": 10, "successes": 10, "errors": 0, "elapsed_seconds": 0.7838622859999305, "successful_rps": 12.75734293970215, "p50_seconds": 0.4336575634952169, "p95_seconds": 0.7340192681040206, "p99_seconds": 0.7722596784304188}, {"size_bytes": 3151219, "side": 1024, "repeat": 2, "concurrency": 10, "attempts": 10, "successes": 10, "errors": 0, "elapsed_seconds": 0.597734743001638, "successful_rps": 16.729828936800814, "p50_seconds": 0.4081998335022945, "p95_seconds": 0.584588757907477, "p99_seconds": 0.5914236595887633}, {"size_bytes": 3151219, "side": 1024, "repeat": 3, "concurrency": 10, "attempts": 10, "successes": 10, "errors": 0, "elapsed_seconds": 0.472148330998607, "successful_rps": 21.179784706322522, "p50_seconds": 0.2796381600055611, "p95_seconds": 0.4425103257497539, "p99_seconds": 0.4638570675504161}, {"size_bytes": 9648062, "side": 1792, "repeat": 1, "concurrency": 10, "attempts": 10, "successes": 10, "errors": 0, "elapsed_seconds": 1.5366208479972556, "successful_rps": 6.507786233040787, "p50_seconds": 1.0274780609979643, "p95_seconds": 1.4637623943453943, "p99_seconds": 1.5201743212681322}, {"size_bytes": 9648062, "side": 1792, "repeat": 2, "concurrency": 10, "attempts": 10, "successes": 10, "errors": 0, "elapsed_seconds": 1.7978311129991198, "successful_rps": 5.56225772693305, "p50_seconds": 1.1837765999953263, "p95_seconds": 1.746605640908092, "p99_seconds": 1.784828035391838}, {"size_bytes": 9648062, "side": 1792, "repeat": 3, "concurrency": 10, "attempts": 10, "successes": 10, "errors": 0, "elapsed_seconds": 1.7773193390021333, "successful_rps": 5.626450903085569, "p50_seconds": 1.0610903210035758, "p95_seconds": 1.7164175714497103, "p99_seconds": 1.7635092142925715}]}
+600
View File
@@ -0,0 +1,600 @@
{
"result": "PASS",
"profile": "closed-loop batch, 10 simultaneous uploads, 3 repeats per size, 1 warmup, all confirmed originals downloaded",
"runs": [
{
"size_bytes": 3151219,
"side": 1024,
"repeat": 1,
"concurrency": 10,
"attempts": 10,
"successes": 10,
"errors": 0,
"elapsed_seconds": 0.7838622859999305,
"successful_rps": 12.75734293970215,
"p50_seconds": 0.4336575634952169,
"p95_seconds": 0.7340192681040206,
"p99_seconds": 0.7722596784304188
},
{
"size_bytes": 3151219,
"side": 1024,
"repeat": 2,
"concurrency": 10,
"attempts": 10,
"successes": 10,
"errors": 0,
"elapsed_seconds": 0.597734743001638,
"successful_rps": 16.729828936800814,
"p50_seconds": 0.4081998335022945,
"p95_seconds": 0.584588757907477,
"p99_seconds": 0.5914236595887633
},
{
"size_bytes": 3151219,
"side": 1024,
"repeat": 3,
"concurrency": 10,
"attempts": 10,
"successes": 10,
"errors": 0,
"elapsed_seconds": 0.472148330998607,
"successful_rps": 21.179784706322522,
"p50_seconds": 0.2796381600055611,
"p95_seconds": 0.4425103257497539,
"p99_seconds": 0.4638570675504161
},
{
"size_bytes": 9648062,
"side": 1792,
"repeat": 1,
"concurrency": 10,
"attempts": 10,
"successes": 10,
"errors": 0,
"elapsed_seconds": 1.5366208479972556,
"successful_rps": 6.507786233040787,
"p50_seconds": 1.0274780609979643,
"p95_seconds": 1.4637623943453943,
"p99_seconds": 1.5201743212681322
},
{
"size_bytes": 9648062,
"side": 1792,
"repeat": 2,
"concurrency": 10,
"attempts": 10,
"successes": 10,
"errors": 0,
"elapsed_seconds": 1.7978311129991198,
"successful_rps": 5.56225772693305,
"p50_seconds": 1.1837765999953263,
"p95_seconds": 1.746605640908092,
"p99_seconds": 1.784828035391838
},
{
"size_bytes": 9648062,
"side": 1792,
"repeat": 3,
"concurrency": 10,
"attempts": 10,
"successes": 10,
"errors": 0,
"elapsed_seconds": 1.7773193390021333,
"successful_rps": 5.626450903085569,
"p50_seconds": 1.0610903210035758,
"p95_seconds": 1.7164175714497103,
"p99_seconds": 1.7635092142925715
}
],
"samples": [
{
"time": 1793371458.0681832,
"containers": [
{
"BlockIO": "0B / 0B",
"CPUPerc": "7.04%",
"Container": "68ab8db39c844427ad170edeb784590708e6fc3e69cd4abe43c05b8b6adce6d3",
"ID": "68ab8db39c84",
"MemPerc": "19.38%",
"MemUsage": "99.22MiB / 512MiB",
"Name": "lyakhonov-lab4-api-1",
"NetIO": "61.5kB / 61.2kB",
"PIDs": "11"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "8.49%",
"Container": "a6106479affd1937a2a56fae0888dc2c155b382a2e1325e94c99194491109dbb",
"ID": "a6106479affd",
"MemPerc": "19.54%",
"MemUsage": "100.1MiB / 512MiB",
"Name": "lyakhonov-lab4-api-2",
"NetIO": "3.22MB / 3.23MB",
"PIDs": "10"
},
{
"BlockIO": "0B / 2.65MB",
"CPUPerc": "2.09%",
"Container": "10138b5c0beefe8a15a6679fdad81ddac663eea21e8f63bf3ca03545c2558f20",
"ID": "10138b5c0bee",
"MemPerc": "5.18%",
"MemUsage": "26.52MiB / 512MiB",
"Name": "lyakhonov-lab4-db-1",
"NetIO": "662kB / 705kB",
"PIDs": "9"
},
{
"BlockIO": "741kB / 0B",
"CPUPerc": "0.18%",
"Container": "e9682a892ad30d5becf1fda8abbc16770aed81f261b0843f9cb047b5085baf76",
"ID": "e9682a892ad3",
"MemPerc": "10.57%",
"MemUsage": "13.52MiB / 128MiB",
"Name": "lyakhonov-lab4-lb-1",
"NetIO": "789MB / 789MB",
"PIDs": "17"
},
{
"BlockIO": "0B / 3.19MB",
"CPUPerc": "2.00%",
"Container": "a6482b44d70a2031a2563b1b72d955435125453a48e95087464775c918801941",
"ID": "a6482b44d70a",
"MemPerc": "39.63%",
"MemUsage": "304.4MiB / 768MiB",
"Name": "lyakhonov-lab4-s3-1",
"NetIO": "4.08MB / 798MB",
"PIDs": "21"
}
]
},
{
"time": 1793371461.407941,
"containers": [
{
"BlockIO": "0B / 0B",
"CPUPerc": "2.06%",
"Container": "68ab8db39c844427ad170edeb784590708e6fc3e69cd4abe43c05b8b6adce6d3",
"ID": "68ab8db39c84",
"MemPerc": "20.62%",
"MemUsage": "105.6MiB / 512MiB",
"Name": "lyakhonov-lab4-api-1",
"NetIO": "31.7MB / 31.7MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "0.88%",
"Container": "a6106479affd1937a2a56fae0888dc2c155b382a2e1325e94c99194491109dbb",
"ID": "a6106479affd",
"MemPerc": "20.64%",
"MemUsage": "105.7MiB / 512MiB",
"Name": "lyakhonov-lab4-api-2",
"NetIO": "34.9MB / 34.9MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 2.74MB",
"CPUPerc": "0.14%",
"Container": "10138b5c0beefe8a15a6679fdad81ddac663eea21e8f63bf3ca03545c2558f20",
"ID": "10138b5c0bee",
"MemPerc": "6.84%",
"MemUsage": "35.02MiB / 512MiB",
"Name": "lyakhonov-lab4-db-1",
"NetIO": "705kB / 746kB",
"PIDs": "13"
},
{
"BlockIO": "741kB / 0B",
"CPUPerc": "0.21%",
"Container": "e9682a892ad30d5becf1fda8abbc16770aed81f261b0843f9cb047b5085baf76",
"ID": "e9682a892ad3",
"MemPerc": "10.60%",
"MemUsage": "13.57MiB / 128MiB",
"Name": "lyakhonov-lab4-lb-1",
"NetIO": "852MB / 853MB",
"PIDs": "17"
},
{
"BlockIO": "0B / 34.8MB",
"CPUPerc": "16.97%",
"Container": "a6482b44d70a2031a2563b1b72d955435125453a48e95087464775c918801941",
"ID": "a6482b44d70a",
"MemPerc": "39.90%",
"MemUsage": "306.5MiB / 768MiB",
"Name": "lyakhonov-lab4-s3-1",
"NetIO": "35.7MB / 830MB",
"PIDs": "21"
}
]
},
{
"time": 1793371464.4601676,
"containers": [
{
"BlockIO": "0B / 0B",
"CPUPerc": "8.26%",
"Container": "68ab8db39c844427ad170edeb784590708e6fc3e69cd4abe43c05b8b6adce6d3",
"ID": "68ab8db39c84",
"MemPerc": "21.66%",
"MemUsage": "110.9MiB / 512MiB",
"Name": "lyakhonov-lab4-api-1",
"NetIO": "63.5MB / 63.4MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "8.14%",
"Container": "a6106479affd1937a2a56fae0888dc2c155b382a2e1325e94c99194491109dbb",
"ID": "a6106479affd",
"MemPerc": "20.75%",
"MemUsage": "106.2MiB / 512MiB",
"Name": "lyakhonov-lab4-api-2",
"NetIO": "66.6MB / 66.6MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 2.84MB",
"CPUPerc": "2.95%",
"Container": "10138b5c0beefe8a15a6679fdad81ddac663eea21e8f63bf3ca03545c2558f20",
"ID": "10138b5c0bee",
"MemPerc": "6.88%",
"MemUsage": "35.23MiB / 512MiB",
"Name": "lyakhonov-lab4-db-1",
"NetIO": "745kB / 784kB",
"PIDs": "13"
},
{
"BlockIO": "741kB / 0B",
"CPUPerc": "0.17%",
"Container": "e9682a892ad30d5becf1fda8abbc16770aed81f261b0843f9cb047b5085baf76",
"ID": "e9682a892ad3",
"MemPerc": "10.80%",
"MemUsage": "13.82MiB / 128MiB",
"Name": "lyakhonov-lab4-lb-1",
"NetIO": "916MB / 916MB",
"PIDs": "17"
},
{
"BlockIO": "0B / 66.4MB",
"CPUPerc": "0.94%",
"Container": "a6482b44d70a2031a2563b1b72d955435125453a48e95087464775c918801941",
"ID": "a6482b44d70a",
"MemPerc": "40.05%",
"MemUsage": "307.6MiB / 768MiB",
"Name": "lyakhonov-lab4-s3-1",
"NetIO": "67.4MB / 861MB",
"PIDs": "21"
}
]
},
{
"time": 1793371467.8057384,
"containers": [
{
"BlockIO": "0B / 0B",
"CPUPerc": "1.27%",
"Container": "68ab8db39c844427ad170edeb784590708e6fc3e69cd4abe43c05b8b6adce6d3",
"ID": "68ab8db39c84",
"MemPerc": "24.28%",
"MemUsage": "124.3MiB / 512MiB",
"Name": "lyakhonov-lab4-api-1",
"NetIO": "105MB / 105MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "1.05%",
"Container": "a6106479affd1937a2a56fae0888dc2c155b382a2e1325e94c99194491109dbb",
"ID": "a6106479affd",
"MemPerc": "21.76%",
"MemUsage": "111.4MiB / 512MiB",
"Name": "lyakhonov-lab4-api-2",
"NetIO": "98.3MB / 98.2MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 2.94MB",
"CPUPerc": "0.38%",
"Container": "10138b5c0beefe8a15a6679fdad81ddac663eea21e8f63bf3ca03545c2558f20",
"ID": "10138b5c0bee",
"MemPerc": "7.74%",
"MemUsage": "39.62MiB / 512MiB",
"Name": "lyakhonov-lab4-db-1",
"NetIO": "786kB / 824kB",
"PIDs": "15"
},
{
"BlockIO": "741kB / 0B",
"CPUPerc": "3.99%",
"Container": "e9682a892ad30d5becf1fda8abbc16770aed81f261b0843f9cb047b5085baf76",
"ID": "e9682a892ad3",
"MemPerc": "10.54%",
"MemUsage": "13.5MiB / 128MiB",
"Name": "lyakhonov-lab4-lb-1",
"NetIO": "989MB / 989MB",
"PIDs": "17"
},
{
"BlockIO": "0B / 108MB",
"CPUPerc": "1.47%",
"Container": "a6482b44d70a2031a2563b1b72d955435125453a48e95087464775c918801941",
"ID": "a6482b44d70a",
"MemPerc": "40.25%",
"MemUsage": "309.1MiB / 768MiB",
"Name": "lyakhonov-lab4-s3-1",
"NetIO": "109MB / 893MB",
"PIDs": "21"
}
]
},
{
"time": 1793371471.140233,
"containers": [
{
"BlockIO": "0B / 0B",
"CPUPerc": "7.55%",
"Container": "68ab8db39c844427ad170edeb784590708e6fc3e69cd4abe43c05b8b6adce6d3",
"ID": "68ab8db39c84",
"MemPerc": "26.00%",
"MemUsage": "133.1MiB / 512MiB",
"Name": "lyakhonov-lab4-api-1",
"NetIO": "202MB / 202MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 0B",
"CPUPerc": "7.05%",
"Container": "a6106479affd1937a2a56fae0888dc2c155b382a2e1325e94c99194491109dbb",
"ID": "a6106479affd",
"MemPerc": "25.00%",
"MemUsage": "128MiB / 512MiB",
"Name": "lyakhonov-lab4-api-2",
"NetIO": "195MB / 195MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 3.03MB",
"CPUPerc": "0.17%",
"Container": "10138b5c0beefe8a15a6679fdad81ddac663eea21e8f63bf3ca03545c2558f20",
"ID": "10138b5c0bee",
"MemPerc": "7.79%",
"MemUsage": "39.86MiB / 512MiB",
"Name": "lyakhonov-lab4-db-1",
"NetIO": "828kB / 863kB",
"PIDs": "15"
},
{
"BlockIO": "741kB / 0B",
"CPUPerc": "10.84%",
"Container": "e9682a892ad30d5becf1fda8abbc16770aed81f261b0843f9cb047b5085baf76",
"ID": "e9682a892ad3",
"MemPerc": "10.60%",
"MemUsage": "13.57MiB / 128MiB",
"Name": "lyakhonov-lab4-lb-1",
"NetIO": "1.18GB / 1.18GB",
"PIDs": "17"
},
{
"BlockIO": "0B / 204MB",
"CPUPerc": "0.62%",
"Container": "a6482b44d70a2031a2563b1b72d955435125453a48e95087464775c918801941",
"ID": "a6482b44d70a",
"MemPerc": "40.63%",
"MemUsage": "312.1MiB / 768MiB",
"Name": "lyakhonov-lab4-s3-1",
"NetIO": "205MB / 990MB",
"PIDs": "21"
}
]
},
{
"time": 1793371474.203735,
"containers": [
{
"BlockIO": "283kB / 9.65MB",
"CPUPerc": "42.97%",
"Container": "68ab8db39c844427ad170edeb784590708e6fc3e69cd4abe43c05b8b6adce6d3",
"ID": "68ab8db39c84",
"MemPerc": "27.88%",
"MemUsage": "142.8MiB / 512MiB",
"Name": "lyakhonov-lab4-api-1",
"NetIO": "298MB / 298MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 17.4MB",
"CPUPerc": "36.05%",
"Container": "a6106479affd1937a2a56fae0888dc2c155b382a2e1325e94c99194491109dbb",
"ID": "a6106479affd",
"MemPerc": "25.02%",
"MemUsage": "128.1MiB / 512MiB",
"Name": "lyakhonov-lab4-api-2",
"NetIO": "292MB / 292MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 3.11MB",
"CPUPerc": "4.78%",
"Container": "10138b5c0beefe8a15a6679fdad81ddac663eea21e8f63bf3ca03545c2558f20",
"ID": "10138b5c0bee",
"MemPerc": "7.84%",
"MemUsage": "40.12MiB / 512MiB",
"Name": "lyakhonov-lab4-db-1",
"NetIO": "867kB / 900kB",
"PIDs": "15"
},
{
"BlockIO": "745kB / 0B",
"CPUPerc": "12.86%",
"Container": "e9682a892ad30d5becf1fda8abbc16770aed81f261b0843f9cb047b5085baf76",
"ID": "e9682a892ad3",
"MemPerc": "10.67%",
"MemUsage": "13.66MiB / 128MiB",
"Name": "lyakhonov-lab4-lb-1",
"NetIO": "1.38GB / 1.38GB",
"PIDs": "17"
},
{
"BlockIO": "0B / 301MB",
"CPUPerc": "27.30%",
"Container": "a6482b44d70a2031a2563b1b72d955435125453a48e95087464775c918801941",
"ID": "a6482b44d70a",
"MemPerc": "40.42%",
"MemUsage": "310.5MiB / 768MiB",
"Name": "lyakhonov-lab4-s3-1",
"NetIO": "302MB / 1.09GB",
"PIDs": "21"
}
]
},
{
"time": 1793371477.556512,
"containers": [
{
"BlockIO": "631kB / 15MB",
"CPUPerc": "49.68%",
"Container": "68ab8db39c844427ad170edeb784590708e6fc3e69cd4abe43c05b8b6adce6d3",
"ID": "68ab8db39c84",
"MemPerc": "30.71%",
"MemUsage": "157.2MiB / 512MiB",
"Name": "lyakhonov-lab4-api-1",
"NetIO": "343MB / 327MB",
"PIDs": "13"
},
{
"BlockIO": "77.8kB / 24.7MB",
"CPUPerc": "51.60%",
"Container": "a6106479affd1937a2a56fae0888dc2c155b382a2e1325e94c99194491109dbb",
"ID": "a6106479affd",
"MemPerc": "29.14%",
"MemUsage": "149.2MiB / 512MiB",
"Name": "lyakhonov-lab4-api-2",
"NetIO": "340MB / 331MB",
"PIDs": "16"
},
{
"BlockIO": "0B / 3.18MB",
"CPUPerc": "0.99%",
"Container": "10138b5c0beefe8a15a6679fdad81ddac663eea21e8f63bf3ca03545c2558f20",
"ID": "10138b5c0bee",
"MemPerc": "7.85%",
"MemUsage": "40.21MiB / 512MiB",
"Name": "lyakhonov-lab4-db-1",
"NetIO": "890kB / 920kB",
"PIDs": "15"
},
{
"BlockIO": "827kB / 4.1kB",
"CPUPerc": "7.90%",
"Container": "e9682a892ad30d5becf1fda8abbc16770aed81f261b0843f9cb047b5085baf76",
"ID": "e9682a892ad3",
"MemPerc": "13.49%",
"MemUsage": "17.27MiB / 128MiB",
"Name": "lyakhonov-lab4-lb-1",
"NetIO": "1.47GB / 1.47GB",
"PIDs": "17"
},
{
"BlockIO": "0B / 301MB",
"CPUPerc": "0.29%",
"Container": "a6482b44d70a2031a2563b1b72d955435125453a48e95087464775c918801941",
"ID": "a6482b44d70a",
"MemPerc": "36.71%",
"MemUsage": "281.9MiB / 768MiB",
"Name": "lyakhonov-lab4-s3-1",
"NetIO": "302MB / 1.09GB",
"PIDs": "21"
}
]
},
{
"time": 1793371480.9294415,
"containers": [
{
"BlockIO": "750kB / 15MB",
"CPUPerc": "13.86%",
"Container": "68ab8db39c844427ad170edeb784590708e6fc3e69cd4abe43c05b8b6adce6d3",
"ID": "68ab8db39c84",
"MemPerc": "27.79%",
"MemUsage": "142.3MiB / 512MiB",
"Name": "lyakhonov-lab4-api-1",
"NetIO": "395MB / 395MB",
"PIDs": "13"
},
{
"BlockIO": "77.8kB / 24.7MB",
"CPUPerc": "1.84%",
"Container": "a6106479affd1937a2a56fae0888dc2c155b382a2e1325e94c99194491109dbb",
"ID": "a6106479affd",
"MemPerc": "26.86%",
"MemUsage": "137.5MiB / 512MiB",
"Name": "lyakhonov-lab4-api-2",
"NetIO": "389MB / 389MB",
"PIDs": "14"
},
{
"BlockIO": "0B / 3.21MB",
"CPUPerc": "2.21%",
"Container": "10138b5c0beefe8a15a6679fdad81ddac663eea21e8f63bf3ca03545c2558f20",
"ID": "10138b5c0bee",
"MemPerc": "7.87%",
"MemUsage": "40.3MiB / 512MiB",
"Name": "lyakhonov-lab4-db-1",
"NetIO": "910kB / 942kB",
"PIDs": "15"
},
{
"BlockIO": "827kB / 4.1kB",
"CPUPerc": "0.51%",
"Container": "e9682a892ad30d5becf1fda8abbc16770aed81f261b0843f9cb047b5085baf76",
"ID": "e9682a892ad3",
"MemPerc": "10.84%",
"MemUsage": "13.88MiB / 128MiB",
"Name": "lyakhonov-lab4-lb-1",
"NetIO": "1.57GB / 1.57GB",
"PIDs": "17"
},
{
"BlockIO": "0B / 397MB",
"CPUPerc": "0.44%",
"Container": "a6482b44d70a2031a2563b1b72d955435125453a48e95087464775c918801941",
"ID": "a6482b44d70a",
"MemPerc": "37.20%",
"MemUsage": "285.7MiB / 768MiB",
"Name": "lyakhonov-lab4-s3-1",
"NetIO": "399MB / 1.18GB",
"PIDs": "21"
}
]
}
],
"cgroup_before": [
{
"id": "68ab8db39c84",
"memory.peak": "94355456",
"memory.current": "88948736",
"cpu.stat": "usage_usec 1520787\nuser_usec 1229926\nsystem_usec 290861\nnr_periods 100\nnr_throttled 20\nthrottled_usec 838500\nnr_bursts 0\nburst_usec 0"
},
{
"id": "a6106479affd",
"memory.peak": "94523392",
"memory.current": "89448448",
"cpu.stat": "usage_usec 1465401\nuser_usec 1200760\nsystem_usec 264641\nnr_periods 97\nnr_throttled 18\nthrottled_usec 858421\nnr_bursts 0\nburst_usec 0"
}
],
"cgroup_after": [
{
"id": "68ab8db39c84",
"memory.peak": "176103424",
"memory.current": "155086848",
"cpu.stat": "usage_usec 6981108\nuser_usec 5342601\nsystem_usec 1638507\nnr_periods 318\nnr_throttled 84\nthrottled_usec 4194115\nnr_bursts 0\nburst_usec 0"
},
{
"id": "a6106479affd",
"memory.peak": "164605952",
"memory.current": "150552576",
"cpu.stat": "usage_usec 6971952\nuser_usec 5392216\nsystem_usec 1579735\nnr_periods 304\nnr_throttled 84\nthrottled_usec 4096903\nnr_bursts 0\nburst_usec 0"
}
]
}
+2
View File
@@ -0,0 +1,2 @@
.venv/Scripts/python scripts/validate_openapi.py
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
+60
View File
@@ -0,0 +1,60 @@
# Согласованность PostgreSQL и S3
Источник истины для доступа/связей — PostgreSQL; исходные bytes — приватный S3.
Upload принимает raw body в ограниченный временный spool (не durable storage), проверяет MIME/целостность/пиксели,
затем выбирает уникальный originals/UUID, берёт транзакционную advisory lock по ключу и выполняет S3 PUT → INSERT Attachment → COMMIT.
201 возвращается только после COMMIT. Оригинал не перекодируется. Сессия и ACL проверяются до чтения body.
## Сбои и восстановление
- Обрыв до PUT: временный spool закрывается, постоянного объекта нет.
- PUT не прошёл: INSERT/COMMIT не выполняются, ответ 503.
- PUT прошёл, INSERT/COMMIT не прошёл или результат COMMIT неизвестен: объект не удаляется вслепую.
Если COMMIT всё же прошёл, удаление уничтожило бы подтверждённое вложение. Reconciler после grace проверяет наличие строки заново.
- Метаданные есть, объекта нет/он повреждён: строка переводится во внутреннее missing. Публичное Attachment ready не подделывается:
GET метаданных/content даёт 503, добавление такого вложения в новое сообщение — 409. Ранее созданное сообщение и его связи остаются.
- Когда оператор вернул оригинал из резервной копии, reconciler читает реальные bytes потоково, сравнивает размер, SHA-256 и MIME.
Только совпадение возвращает ready. Сверка сама не может восстановить утраченные bytes; backup/репликация здесь не реализованы.
## Алгоритм
1. Время cutoff фиксируется в начале запуска. LIST обходится страницами (default 100).
2. Для каждого объекта попробовать ту же advisory lock. Активный uploader/другой reconciler приводит к skip.
3. Под блокировкой повторно прочитать метаданные; любая существующая строка сохраняет объект, даже если сообщение ещё не создано.
4. При отсутствии строки заново HEAD; только LastModified <= cutoff позволяет удаление orphan. Иначе fresh_kept.
5. Метаданные обойти keyset-страницами по UUID. Под той же блокировкой и FOR UPDATE проверить HEAD и SHA-256 тела блоками 64 KiB.
404 означает missing, сетевой/авторизационный/серверный сбой не считается отсутствием и прерывает проход.
6. Dry-run имеет те же проверки, но не меняет ни один store. Apply атомарно фиксирует каждое изменение метаданных;
повтор после сбоя или конкурентный проход безопасен. Глобального snapshot между двумя store нет, изменения во время прохода могут попасть в следующий.
Защита от гонки orphan/COMMIT — общая блокировка, а не только ожидание времени.
Область originals доступна на запись только приложению/оператору учебного стенда. Протокол не защищает от администратора,
который обходит advisory lock и одновременно перезаписывает/удаляет объекты. Случайная hash-коллизия вызывает лишний skip/ожидание, а не удаление используемого объекта.
Метаданные и связи сообщений алгоритм не удаляет вообще. Уникальный ключ не переиспользуется upload; PUT имеет If-None-Match: *.
## Запуск
```sh
# Dry-run по умолчанию:
docker compose run --rm --no-deps api python -m src.reconcile
# Применение, обычный grace 1 час:
docker compose run --rm --no-deps api python -m src.reconcile --apply
```
Сервис reconciler делает apply каждые 300 секунд, grace=3600 секунд; после ошибки пишет только класс ошибки и повторяет проход.
Полный цикл обнаружения старого orphan — grace + период запуска + длительность прохода; при недоступных stores SLA не гарантируется.
При benchmark сервис останавливают, затем восстанавливают, чтобы его чтение/хеширование не искажало измерения.
В тесте используются grace=5 секунд и искусственные synthetic objects; этот интервал не является эксплуатационной рекомендацией.
Минимально разрешено 5 секунд, default остаётся 3600. CPU/RAM/трафик сверки растут с количеством объектов и bytes;
RAM ограничена размером страницы и chunk, а не размером всего bucket.
## Ограничения памяти/таймаутов API
На реплику один upload внутри semaphore; очередь не более общего лимита 100 запросов, ожидание слота <=25 с.
Body <=10 MiB контролируется по объявленному размеру и фактически прочитанным chunks, приём <=20 с.
PNG/JPEG проверяются до декодирования по размеру <=40 млн px; Pillow verify и затем load обнаруживают повреждённые потоки.
Наихудший framebuffer порядка 160 MB на одну декодируемую картинку; API ограничена 512 MiB. Потоковый приём не означает нулевую RAM декодера.
Временный файл используется только до синхронного PUT и закрывается при ошибке; API не хранит durable оригинал на своём диске.
S3 connect=2 с, read=5 с, SDK без автоматических retry; LB client=60 с/server=45 с, без повторов POST.
Readiness требует PostgreSQL и доступного S3 LIST в рабочем prefix, Redis необязателен. После обнаружения S3-отказа LB исключает обе API;
это осознанная граница доступности всего стенда. Ошибка LB может не иметь API-заголовков/JSON.
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
export MINIO_ROOT_USER="$(cat "$MINIO_ROOT_USER_FILE")"
export MINIO_ROOT_PASSWORD="$(cat "$MINIO_ROOT_PASSWORD_FILE")"
exec minio "$@"
+2
View File
@@ -0,0 +1,2 @@
-r requirements-dev.txt
matplotlib==3.10.7
+1 -1
View File
@@ -10,7 +10,7 @@ def compose(*args):
return subprocess.check_output(base+list(args),text=True).strip()
mode=sys.argv[1]
if mode=='restart':
compose('restart','api','db','redis','s3','lb')
compose('restart','api','db','redis','s3','lb','reconciler')
elif mode=='stop-one':
target=os.environ['TARGET_INSTANCE_ID']
for cid in compose('ps','-q','api').splitlines():
+36
View File
@@ -0,0 +1,36 @@
"""Host-side Docker CPU/RAM sampling during the real upload experiment."""
import json
from pathlib import Path
import subprocess
import time
ROOT=Path(__file__).resolve().parents[1]
base=['docker','compose','--project-directory',str(ROOT),'-p','lyakhonov-lab4']
def cgroups():
ids=subprocess.check_output(base+['ps','-q','api'],text=True).split()
result=[]
for cid in ids:
code="from pathlib import Path; import json; print(json.dumps({name:Path('/sys/fs/cgroup/'+name).read_text().strip() for name in ('memory.peak','memory.current','cpu.stat')}))"
raw=subprocess.check_output(['docker','exec',cid,'python','-c',code],text=True)
result.append({'id':cid[:12],**json.loads(raw)})
return result
subprocess.check_call(base+['stop','reconciler'],stdout=subprocess.DEVNULL)
try:
before=cgroups()
cmd=base+['run','--rm','--no-deps','-T','-v',str(ROOT)+':/suite:ro','-w','/suite','api','python','student-tests/upload_load.py']
with (ROOT/'evidence/upload-load-output.txt').open('w',encoding='utf-8') as output:
proc=subprocess.Popen(cmd,stdout=output)
samples=[]
while proc.poll() is None:
ids=subprocess.check_output(base+['ps','-q','api','db','s3','lb'],text=True).split()
if ids:
raw=subprocess.check_output(['docker','stats','--no-stream','--format','{{json .}}']+ids,text=True)
samples.append({'time':time.time(),'containers':[json.loads(x) for x in raw.splitlines()]})
time.sleep(.3)
if proc.returncode: raise SystemExit(proc.returncode)
text=(ROOT/'evidence/upload-load-output.txt').read_text(encoding='utf-8').strip()
result=json.loads(text.splitlines()[-1]); result['samples']=samples
result['cgroup_before']=before; result['cgroup_after']=cgroups()
(ROOT/'evidence/upload-load.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
finally:
subprocess.check_call(base+['start','reconciler'],stdout=subprocess.DEVNULL)
print('PASS: upload experiment and Docker CPU/RAM samples saved; batches:',len(result['runs']))
+118
View File
@@ -0,0 +1,118 @@
"""Repeatable bounded-memory reconciliation. Dry-run is the default."""
import argparse
from collections import Counter
from datetime import datetime, timezone
import hashlib
import json
import time
from botocore.exceptions import ClientError
from src.objects import client, BUCKET, object_lock
from src.storage import storage
def absent(exc):
return exc.response['Error']['Code'] in ('404','NoSuchKey','NotFound')
def reconcile(apply=False,grace_seconds=3600,page_size=100,output=None):
if grace_seconds<5 or not 1<=page_size<=1000:
raise ValueError('grace must be >=5 seconds; page size 1..1000')
started=time.monotonic(); s3=client(); counts=Counter()
# Fixed cutoff at run start protects objects created during the traversal.
cutoff=datetime.now(timezone.utc).timestamp()-grace_seconds
# Streaming listing; no full bucket/object-body materialization.
paginator=s3.get_paginator('list_objects_v2')
for page in paginator.paginate(Bucket=BUCKET,Prefix='originals/',PaginationConfig={'PageSize':page_size}):
counts['list_requests']+=1
for obj in page.get('Contents',[]):
counts['objects_scanned']+=1; key=obj['Key']
with storage.pool.connection() as conn:
if not object_lock(conn,key,wait=False):
counts['locked_skipped']+=1; continue
row=conn.execute('SELECT id FROM attachments WHERE object_key=%s',(key,)).fetchone()
if row:
counts['referenced_kept']+=1; continue
counts['head_requests']+=1
try: head=s3.head_object(Bucket=BUCKET,Key=key)
except ClientError as exc:
if absent(exc): continue
raise
if head['LastModified'].timestamp()>cutoff:
counts['fresh_kept']+=1; continue
counts['orphan_candidates']+=1
if apply:
# Only application/reconciler may write this namespace; both hold this lock.
s3.delete_object(Bucket=BUCKET,Key=key)
counts['objects_deleted']+=1
# Keyset pages keep RAM bounded even for a large metadata table.
last='00000000-0000-0000-0000-000000000000'
while True:
with storage.pool.connection() as conn:
rows=conn.execute('SELECT id,object_key FROM attachments WHERE id>%s ORDER BY id LIMIT %s',(last,page_size)).fetchall()
if not rows: break
counts['db_pages']+=1
for item in rows:
last=str(item['id']); counts['metadata_scanned']+=1
with storage.pool.connection() as conn:
if not object_lock(conn,item['object_key'],wait=False):
counts['locked_skipped']+=1; continue
row=conn.execute('SELECT * FROM attachments WHERE id=%s FOR UPDATE',(item['id'],)).fetchone()
if not row: continue
counts['head_requests']+=1
try:
head=s3.head_object(Bucket=BUCKET,Key=row['object_key'])
except ClientError as exc:
if not absent(exc): raise
counts['missing_objects']+=1
if row['state']=='ready':
counts['mark_missing_candidates']+=1
if apply:
conn.execute("UPDATE attachments SET state='missing',updated_at=clock_timestamp() WHERE id=%s",(row['id'],))
counts['metadata_marked_missing']+=1
continue
# Verify actual bytes, never trust an ETag or user-provided hash metadata.
digest=hashlib.sha256(); size=0
counts['get_requests']+=1
obj=s3.get_object(Bucket=BUCKET,Key=row['object_key'])
try:
for chunk in obj['Body'].iter_chunks(64*1024):
size+=len(chunk); counts['bytes_verified']+=len(chunk)
if size>10*1024*1024: break
digest.update(chunk)
finally: obj['Body'].close()
valid=(size==row['size_bytes'] and digest.hexdigest()==row['sha256'] and head['ContentType']==row['content_type'])
desired='ready' if valid else 'missing'
counts['valid_objects' if valid else 'corrupt_objects']+=1
if desired!=row['state']:
counts['restore_candidates' if valid else 'mark_missing_candidates']+=1
if apply:
conn.execute('UPDATE attachments SET state=%s,updated_at=clock_timestamp() WHERE id=%s',(desired,row['id']))
counts['metadata_restored' if valid else 'metadata_marked_missing']+=1
result={'apply':apply,'grace_seconds':grace_seconds,'page_size':page_size,
'elapsed_seconds':round(time.monotonic()-started,6),'counts':dict(counts)}
if output:
from pathlib import Path
Path(output).write_text(json.dumps(result,indent=2),encoding='utf-8')
return result
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply',action='store_true')
parser.add_argument('--grace-seconds',type=int,default=3600)
parser.add_argument('--page-size',type=int,default=100)
parser.add_argument('--interval',type=int,default=0,help='repeat every N seconds, 0 = one shot')
args=parser.parse_args()
if args.interval and args.interval<5:
parser.error('interval must be >=5 seconds')
storage.pool.open(wait=True)
try:
while True:
try:
print(json.dumps(reconcile(args.apply,args.grace_seconds,args.page_size)),flush=True)
except Exception as exc:
# Do not log endpoint URLs, DSNs, object keys or credentials.
print(json.dumps({'result':'failed','error_type':type(exc).__name__}),flush=True)
if not args.interval: raise SystemExit(1) from None
if not args.interval: break
time.sleep(args.interval)
finally: storage.pool.close()
if __name__=='__main__': main()
+5
View File
@@ -9,6 +9,7 @@ from PIL import Image, UnidentifiedImageError
from fastapi import APIRouter, Depends, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from starlette.responses import StreamingResponse
from starlette.requests import ClientDisconnect
from src.routes.common import require_user, make_error, get_request_id
from src.storage import storage, timestamp
from src.objects import client, BUCKET, object_lock
@@ -99,6 +100,8 @@ async def upload(request:Request,chat_id:uuid.UUID,filename:str='',actor:str=Dep
await asyncio.wait_for(receive(),timeout=20)
await run_in_threadpool(stream.seek,0)
await run_in_threadpool(inspect_image,stream,mime)
except ClientDisconnect:
raise error(request,400,'invalid_request','upload disconnected') from None
except asyncio.TimeoutError:
raise error(request,400,'invalid_request','upload timed out') from None
except InvalidImage as exc:
@@ -123,6 +126,8 @@ def get_attachment(request:Request,attachment_id:uuid.UUID,actor:str=Depends(req
@router.get('/api/v1/attachments/{attachment_id}/content')
def content(request:Request,attachment_id:uuid.UUID,variant:str='original',actor:str=Depends(require_user)):
row=accessible(request,attachment_id,actor)
if variant not in ('original','thumbnail','crop','optimized'):
raise error(request,400,'invalid_request','invalid variant')
if variant!='original':
raise error(request,404,'not_found','variant not found')
obj=client().get_object(Bucket=BUCKET,Key=row['object_key'])
+105
View File
@@ -0,0 +1,105 @@
"""Real HTTP negative/transaction tests against the isolated lab4 stack."""
import base64
from concurrent.futures import ThreadPoolExecutor
import hashlib
import http.client
import io
import json
from pathlib import Path
import socket
import sys
import time
from urllib.parse import quote
import uuid
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client, check
from PIL import Image
from botocore import UNSIGNED
from botocore.config import Config
from botocore.exceptions import ClientError
import boto3
from src.storage import storage
from src.objects import client,BUCKET
def main():
c=Client('http://lb:8080',timeout=40)
alice,bob,eve,chat=c.bootstrap(); path='/api/v1/chats/'+chat['id']
png=(Path('tests/fixtures/sample.png')).read_bytes()
def upload(data=png,mime='image/png',filename='sample.png',expected=201):
return c.call('POST',path+'/attachments?filename='+quote(filename,safe=''),expected,
actor=alice,raw=data,headers={'Content-Type':mime},schema='Attachment' if expected==201 else None)
att=upload()['json']
for name in ('../x.png','a\\b.png','a/b.png','a\x00.png','a\n.png',''):
upload(filename=name,expected=400)
upload(data=b'not an image',expected=415)
upload(data=png[:100],expected=415)
upload(mime='image/jpeg',expected=415)
upload(mime='application/octet-stream',expected=415)
upload(data=b'x'*(10*1024*1024+1),expected=413)
# Chunked body exercises the streaming limit with no Content-Length.
connection=http.client.HTTPConnection('lb',8080,timeout=30)
connection.request('POST',path+'/attachments?filename=chunked.png',body=iter([b'x'*1048576]*11),
headers={'Authorization':'Bearer '+alice['token'],'Content-Type':'image/png'},encode_chunked=True)
response=connection.getresponse(); payload=json.loads(response.read()); connection.close()
check(response.status==413 and payload['error']['code']=='payload_too_large','chunked byte limit failed')
# Pixel limit checked before decompression. No huge fixture stored in Git.
image=Image.new('L',(8001,5000)); buff=io.BytesIO(); image.save(buff,format='PNG')
upload(data=buff.getvalue(),expected=413)
del image,buff
image=Image.new('RGB',(8000,5000),(1,2,3)); buff=io.BytesIO(); image.save(buff,format='PNG')
upload(data=buff.getvalue()); del image,buff
buff=io.BytesIO(); Image.new('RGB',(48,32),(90,20,10)).save(buff,format='JPEG')
jpeg=buff.getvalue(); j=upload(data=jpeg,mime='image/jpeg',filename='фото.jpg')['json']
check(c.call('GET','/api/v1/attachments/'+j['id']+'/content',actor=bob)['bytes']==jpeg,'JPEG changed')
upload(data=jpeg[:-20],mime='image/jpeg',expected=415)
c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',404,actor=bob)
c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=unknown',400,actor=bob)
c.call('POST',path+'/messages',404,actor=alice,body={'text':'','attachment_ids':[str(uuid.uuid4())]},headers={'Idempotency-Key':uuid.uuid4().hex})
other=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'other','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=alice,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
c.call('POST',path+'/messages',400,actor=alice,body={'text':'','attachment_ids':[att['id'],att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
key=uuid.uuid4().hex
with ThreadPoolExecutor(max_workers=16) as pool:
messages=list(pool.map(lambda _:Client('http://lb:8080',timeout=40).message(alice,chat,'',key=key,attachments=[att['id']])['json'],range(16)))
check(len({m['id'] for m in messages})==1,'concurrent attachment retry duplicated')
c.call('POST',path+'/messages',409,actor=alice,body={'text':'','attachment_ids':[j['id']]},headers={'Idempotency-Key':key})
text_key=uuid.uuid4().hex
m=c.message(alice,chat,'semantic equality',key=text_key)['json']
check(c.message(alice,chat,'semantic equality',key=text_key,attachments=[])['json']==m,'default [] differs')
# Direct unauthenticated bucket read must fail. No public S3 host port needed.
storage.pool.open(wait=True)
s3=client()
with storage.pool.connection() as conn:
row=conn.execute('SELECT object_key FROM attachments WHERE id=%s',(att['id'],)).fetchone()
unsigned=boto3.client('s3',endpoint_url='http://s3:9000',config=Config(signature_version=UNSIGNED))
try: unsigned.get_object(Bucket=BUCKET,Key=row['object_key'])
except ClientError as exc: check(exc.response['ResponseMetadata']['HTTPStatusCode']==403,'unsigned wrong error')
else: raise AssertionError('public object')
for operation in (lambda:s3.list_buckets(),lambda:s3.put_object(Bucket=BUCKET,Key='outside-prefix',Body=b'x'),lambda:s3.delete_bucket(Bucket=BUCKET)):
try: operation()
except ClientError as exc: check(exc.response['ResponseMetadata']['HTTPStatusCode']==403,'policy wrong error')
else: raise AssertionError('excessive app S3 privileges')
# Real TCP disconnect before declared length: no S3 PUT or metadata commit.
before=sum(1 for page in s3.get_paginator('list_objects_v2').paginate(Bucket=BUCKET,Prefix='originals/') for _ in page.get('Contents',[]))
sock=socket.create_connection(('lb',8080))
header=('POST '+path+'/attachments?filename=abort.png HTTP/1.1\r\nHost: lb\r\nAuthorization: Bearer '+alice['token']+'\r\nContent-Type: image/png\r\nContent-Length: 1000000\r\n\r\n').encode()
sock.sendall(header+png[:100]); sock.close(); time.sleep(1)
after=sum(1 for page in s3.get_paginator('list_objects_v2').paginate(Bucket=BUCKET,Prefix='originals/') for _ in page.get('Contents',[]))
check(before==after,'interrupted upload created object')
# Inject DB failure AFTER a real S3 PUT, restricted to this new synthetic chat.
with storage.pool.connection() as conn:
conn.execute("CREATE OR REPLACE FUNCTION lab4_test_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.chat_id='"+chat['id']+"'::uuid THEN RAISE EXCEPTION 'synthetic failure'; END IF; RETURN NEW; END $$")
conn.execute('CREATE TRIGGER lab4_test_failure BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION lab4_test_failure()')
try: upload(expected=500)
finally:
with storage.pool.connection() as conn:
conn.execute('DROP TRIGGER IF EXISTS lab4_test_failure ON attachments')
conn.execute('DROP FUNCTION IF EXISTS lab4_test_failure()')
after_failure=sum(1 for page in s3.get_paginator('list_objects_v2').paginate(Bucket=BUCKET,Prefix='originals/') for _ in page.get('Contents',[]))
check(after_failure==after+1,'did not exercise S3/DB gap')
upload()
storage.pool.close()
print(json.dumps({'result':'PASS','concurrent_retries':16,'failure_after_s3_put':True,'interrupted_upload_no_object':True,'private_bucket':True,'restricted_credentials':True}))
if __name__=='__main__': main()
+54
View File
@@ -0,0 +1,54 @@
"""Ten simultaneous HTTP uploads, bounded synthetic PNGs, no retries."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import io
import json
from pathlib import Path
import random
import statistics
import sys
import threading
import time
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client,check
from PIL import Image
def percentile(values,p):
if not values: return None
values=sorted(values); pos=(len(values)-1)*p; lo=int(pos); hi=min(lo+1,len(values)-1)
return values[lo]+(values[hi]-values[lo])*(pos-lo)
def main():
c=Client('http://lb:8080',timeout=40)
alice,bob,eve,chat=c.bootstrap()
results=[]
for side in (1024,1792):
rng=random.Random(2301+side)
image=Image.frombytes('RGB',(side,side),rng.randbytes(side*side*3))
buff=io.BytesIO(); image.save(buff,format='PNG'); data=buff.getvalue(); del image,buff
check(len(data)<=10*1024*1024,'invalid benchmark size')
# Warmup separately; no retry hides transient failures.
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=warmup.png',201,actor=alice,raw=data,headers={'Content-Type':'image/png'},schema='Attachment')
for repeat in range(3):
barrier=threading.Barrier(11); start_event=threading.Event()
def task(_):
local=Client('http://lb:8080',timeout=40); barrier.wait(); start_event.wait(); started=time.monotonic()
try:
att=local.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=load.png',201,actor=alice,raw=data,headers={'Content-Type':'image/png'},schema='Attachment')['json']
check(att['sha256']==hashlib.sha256(data).hexdigest(),'bad checksum')
return {'ok':True,'seconds':time.monotonic()-started,'id':att['id']}
except Exception as exc:
return {'ok':False,'seconds':time.monotonic()-started,'error':type(exc).__name__}
with ThreadPoolExecutor(max_workers=10) as pool:
futures=[pool.submit(task,i) for i in range(10)]
barrier.wait(); started=time.monotonic(); start_event.set()
rows=[future.result() for future in futures]
elapsed=time.monotonic()-started
times=[r['seconds'] for r in rows if r['ok']]
for row in rows:
if row['ok']:
check(c.call('GET','/api/v1/attachments/'+row['id']+'/content',actor=bob)['bytes']==data,'confirmed upload not durable')
results.append({'size_bytes':len(data),'side':side,'repeat':repeat+1,'concurrency':10,'attempts':10,'successes':len(times),'errors':10-len(times),'elapsed_seconds':elapsed,'successful_rps':len(times)/elapsed,'p50_seconds':percentile(times,.5),'p95_seconds':percentile(times,.95),'p99_seconds':percentile(times,.99)})
print(json.dumps({'result':'PASS' if all(r['errors']==0 for r in results) else 'FAIL','profile':'closed-loop batch, 10 simultaneous uploads, 3 repeats per size, 1 warmup, all confirmed originals downloaded','runs':results}))
check(all(r['errors']==0 for r in results),'upload failures')
if __name__=='__main__': main()