Repository navigation
build: serve with Gunicorn - #120
Conversation
When several workers of the app start at the same time, each adds keys to services registered without one. A worker that read such a service before another worker added its key found the service itself under that key and reported it as a duplicate, so it failed to start. Keys added concurrently to the same service are now kept. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check admin groups and the service info, and add missing keys of services, in create_app() instead of main(), so that a WSGI server that calls the factory (e.g., in each Gunicorn worker) runs them too and fails to start if they fail. main() keeps running the app with Flask's development server, for development. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The image ran the app with Flask's development server, which has no worker management, timeouts or hardening. It now runs Gunicorn 26 with the app factory (`cloud_registry.app:create_app()`), with settings in `cloud_registry/gunicorn_config.py`, overridable via `GUNICORN_CMD_ARGS`: - one gthread worker with 4 threads (a worker takes about 55 MiB, so two would exceed the chart's 128 MiB limit); - worker timeout 30 s, graceful timeout 20 s (less than the pod's termination grace period), keep-alive 5 s; - explicit limits of the request line and headers; - error log to stderr, no access log (the app logs each request); - heartbeat files in /dev/shm if writable, else in the temporary directory, so that a read-only root file system works; - no control socket, which would be created in the home directory. The app is not preloaded, as MongoDB clients must not be shared across forks: each worker creates the app and runs the startup checks, and Gunicorn exits if a worker fails to boot. `python -m cloud_registry.app` keeps running the development server. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add `cloud_registry.gunicorn` (workers, threads, timeout, gracefulTimeout, keepalive, extraArgs), with schema entries, rendered into `GUNICORN_CMD_ARGS`, which overrides the image's settings. The defaults are the image's. Further options are single-quoted, as Gunicorn splits the variable like shell words, so the schema rejects single quotes in them. The termination grace period of the pod is now derived from the graceful timeout (10 seconds longer; 30 seconds by default, as before), so that workers can finish their requests before they are killed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pass the host's `GUNICORN_CMD_ARGS` to the app container (empty by default), so that Gunicorn's settings can be changed without editing the Compose file. Note in the base config that `server.host` and `server.port` apply to the development server only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe Gunicorn's settings and how to change them (README, Server), the chart's `cloud_registry.gunicorn` values and their memory needs (deployment/README.md, Server), that probes are served by the same threads as other requests, that `server.host` and `server.port` apply to the development server only, and that the app belongs behind a proxy that buffers requests. Closes #116 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Concurrent runs of the function (e.g., in each worker on startup) are safe, but services registered without keys while it runs (e.g., by an app of an older version) are not; the docstring said both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Gunicorn stops accepting connections on SIGTERM at once, while the ingress controller and the Service may still send requests to the pod for a few seconds (the development server ignored SIGTERM as PID 1, so it served until it was killed). The chart now adds a preStop hook that keeps the app serving for `cloud_registry.preStopSleepSeconds` (default 5; 0 omits the hook), with Python, as the image need not have `sleep`. The termination grace period is that delay plus the graceful timeout plus a margin of 10 seconds (one helper), i.e., 35 seconds by default. Idle keep-alive connections are now closed after 75 seconds instead of 5, i.e., later than ingress-nginx closes its upstream connections (60 seconds): otherwise, nginx may reuse a connection just as Gunicorn closes it, failing the request with 502 (non-idempotent requests are not retried). gthread workers keep idle connections in their poller, not in threads, up to `worker_connections` (1000). Also: - describe `timeout` correctly: it restarts workers whose main loop does not respond; requests stuck in threads don't count; - test that the chart's container port, probes and Service target the port Gunicorn binds, and that the image's health check does; - move loading Gunicorn's settings to `tests/gunicorn_settings.py`, using the image's command from the Dockerfile and restoring the arguments, environment and current directory; - check the specific schema error of each invalid chart value; - document that config overlays can't change Gunicorn's address. Closes #116 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Idle keep-alive connections (e.g., of browsers) keep Gunicorn workers until the graceful timeout (20 seconds), longer than Docker's default stop timeout of 10 seconds, so the server was killed. Set stop_grace_period to 30 seconds, note in the deployment README that shutdown usually takes the full graceful timeout behind a proxy, and say correctly which requests nginx does not retry (non-idempotent). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThe PR replaces Flask's development server with a production Gunicorn setup across the image, Compose, and Helm chart, moving startup validation into the post-fork app factory, hardening concurrent initialization and graceful shutdown, and adding configuration, tests, and deployment documentation. Sequence diagram for post-fork startup validationsequenceDiagram
participant Gunicorn
participant Worker
participant AppFactory as create_app
participant MongoDB
Gunicorn->>Worker: fork worker
Worker->>AppFactory: create_app()
AppFactory->>MongoDB: create MongoDB clients
AppFactory->>AppFactory: check_admin_groups()
AppFactory->>AppFactory: check_service_info()
AppFactory->>AppFactory: add_service_keys()
alt startup check fails
AppFactory-->>Worker: raise startup error
Worker-->>Gunicorn: worker boot failure
Gunicorn-->>Gunicorn: exit
else checks pass
AppFactory-->>Worker: return app
Worker-->>Gunicorn: worker ready
end
Sequence diagram for graceful Kubernetes shutdownsequenceDiagram
participant Kubernetes
participant Pod
participant Proxy
participant Gunicorn
participant Worker
Kubernetes->>Pod: delete pod
Pod->>Pod: preStop sleep
Proxy->>Worker: serve requests during delay
Kubernetes->>Gunicorn: SIGTERM
Gunicorn->>Worker: stop accepting connections
Worker-->>Gunicorn: finish requests
Gunicorn-->>Pod: exit within graceful timeout
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #120 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 9 10 +1
Lines 676 698 +22
=========================================
+ Hits 676 698 +22 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 9 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="deployment/templates/_helpers.tpl" line_range="217" />
<code_context>
+ "--keep-alive" (int $g.keepalive)
+-}}
+{{- range $g.extraArgs -}}
+{{- $args = append $args (squote .) -}}
+{{- end -}}
+{{- join " " $args -}}
</code_context>
<issue_to_address>
**App becomes unreachable**
When a chart or Compose operator overrides Gunicorn’s bind port through the exposed options, `gunicornArgs` lets Gunicorn listen on the override port, but the chart’s container port, probes and Service—and Compose’s published port—remain on 8080. Probes fail or requests cannot reach the app.
Reject bind overrides or make the chart and Compose port settings follow the effective Gunicorn bind.
Also at `docker-compose.yaml:29-30`, `deployment/templates/cloud-registry-deploy.yaml:37`, `deployment/templates/_helpers.tpl:229`.
</issue_to_address>
### Comment 2
<location path="deployment/templates/_helpers.tpl" line_range="217" />
<code_context>
+ "--keep-alive" (int $g.keepalive)
+-}}
+{{- range $g.extraArgs -}}
+{{- $args = append $args (squote .) -}}
+{{- end -}}
+{{- join " " $args -}}
</code_context>
<issue_to_address>
**Workers inherit MongoDB clients**
When `extraArgs` contains Gunicorn’s `--preload` option, gunicorn calls `create_app()` in the master before forking, so workers inherit the MongoDB clients created during startup instead of creating clients after the fork. Database operations in workers can fail or hang.
Prevent `--preload` from being enabled while the app requires post-fork MongoDB clients.
</issue_to_address>
### Comment 3
<location path="cloud_registry/ga4gh/registry/service.py" line_range="623" />
<code_context>
+ Concurrent runs of this function are safe (e.g., in each worker of the
+ app on startup): keys added by another run are kept. Services registered
+ without keys while it runs (e.g., by an app of an older version) are not
+ safe: they may be missed or reported as duplicates.
+
Raises:
</code_context>
<issue_to_address>
**Duplicate services get registered**
When an older app instance writes a service without `_serviceKey` after the backfill scan has passed it, `add_service_keys()` leaves the new service unindexed, and later duplicate checks can miss it; another service with the same URL and API type is then registered.
Ensure the backfill accounts for keyless services written by older app instances before startup checks complete.
</issue_to_address>
### Comment 4
<location path="deployment/templates/_helpers.tpl" line_range="217" />
<code_context>
+ "--keep-alive" (int $g.keepalive)
+-}}
+{{- range $g.extraArgs -}}
+{{- $args = append $args (squote .) -}}
+{{- end -}}
+{{- join " " $args -}}
</code_context>
<issue_to_address>
**Requests are interrupted during shutdown**
When `extraArgs` sets `--graceful-timeout` higher than `cloud_registry.gunicorn.gracefulTimeout`, gunicorn uses the later override, but `terminationGracePeriod` still budgets only the configured `gracefulTimeout`. Kubernetes can kill Gunicorn before its drain finishes, interrupting in-flight requests.
Reject graceful-timeout overrides or calculate the pod termination grace period from the effective timeout.
Also at `deployment/templates/_helpers.tpl:218`, `deployment/templates/_helpers.tpl:229-230`.
</issue_to_address>
### Comment 5
<location path="cloud_registry/gunicorn_config.py" line_range="23-25" />
<code_context>
+bind = ["0.0.0.0:8080"]
+
+# One process with a few threads, as each worker loads the whole app
+worker_class = "gthread"
+workers = 1
+threads = 4
+
+# Workers whose main loop does not report to Gunicorn for `timeout` seconds
</code_context>
<issue_to_address>
**Slow uploads exhaust request threads**
When an unauthenticated client sends a chunked request body slowly through an OpenShift Route, gunicorn's four `gthread` threads block in `check_streamed_size()` while `request.get_data()` reads the body, before Connexion checks authentication. Once all threads are occupied, the app stops serving other requests, including probes, until the clients finish sending.
Enforce a bounded request-read deadline or ensure every supported public route buffers request bodies before forwarding them to Gunicorn.
</issue_to_address>
### Comment 6
<location path="cloud_registry/gunicorn_config.py" line_range="25" />
<code_context>
+# One process with a few threads, as each worker loads the whole app
+worker_class = "gthread"
+workers = 1
+threads = 4
+
+# Workers whose main loop does not report to Gunicorn for `timeout` seconds
</code_context>
<issue_to_address>
**Busy workers fail liveness probes**
When all four request threads remain occupied long enough for three liveness probes to time out, the chart’s liveness probe shares the four Gunicorn request threads. If long-running requests occupy all threads, the probe times out three times and Kubernetes restarts the container, interrupting those requests without establishing that the worker is unhealthy.
Make liveness independent of the request thread pool, or otherwise ensure ordinary request saturation does not trigger container restarts.
</issue_to_address>
### Comment 7
<location path="cloud_registry/ga4gh/registry/service.py" line_range="638" />
<code_context>
problems.append(f"'{service['id']}': {exc.description}")
continue
existing = collection.find_one({KEY: key}, {"_id": False, "id": True})
+ if existing is not None and existing["id"] == service["id"]:
+ continue # added concurrently, e.g., by another worker
if existing is not None:
</code_context>
<issue_to_address>
**Backfill stores a stale service key**
When a legacy app replaces a keyless service after a new worker reads it but before that worker backfills its key, `add_service_keys()` can read the old service contents, then `update_one()` matches only its ID and missing key and writes the old contents’ key onto a legacy replacement. The new same-ID check then accepts that key without validating it against the replacement, so later duplicate checks miss the service’s actual URL and API type.
Make the backfill update conditional on the URL and type used to derive the key, and retry or skip when those fields changed.
</issue_to_address>
### Comment 8
<location path="README.md" line_range="418-420" />
<code_context>
chart][deployment-instructions] uses the same mechanism: it renders its
-`config` value (in a values file per deployment) into an overlay.
+`config` value (in a values file per deployment) into an overlay. Overlays
+cannot change the address the image listens on: `server.host` and
+`server.port` apply to the development server only, not to Gunicorn (see
+[Server](#server)).
Each deployment must set two values that depend on it, otherwise the app
</code_context>
<issue_to_address>
**Production port instructions conflict**
When a deployer follows the Usage instructions and changes `server.port` for the production image, the Usage instructions imply that changing `server.port` moves production traffic, while the server documentation says Gunicorn still listens on 8080. Requests to the configured port fail.
Update the Usage instructions to clarify that `server.port` does not change Gunicorn’s production port.
Also at `README.md:474`.
</issue_to_address>
### Comment 9
<location path="tests/test_app.py" line_range="770" />
<code_context>
- cloud_registry.app.main()
+ cloud_registry.app.create_app()
- assert ports == [8080]
assert services.find_one({"id": "OLD"})["_serviceKey"]
# FOCA configures logging to stderr
</code_context>
<issue_to_address>
**Incorrect service keys pass startup test**
When the factory stores a nonempty key other than the expected service key, in `test_create_app_checks`, `tests/test_app.py:769` checks only that `_serviceKey` is truthy, so a nonempty but incorrect key passes and the test misses invalid keys stored during startup.
Assert that the stored key equals the expected `service_key(SERVICE)`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 9 findings to address first, and gunicorn now serves production traffic, and its startup checks run in each worker; a bad server or shutdown setting can leave pods unable to serve requests or cause failed requests during rollout. Reverting can restore service, but it cannot undo an outage that already occurred; missing service keys can be repaired by rerunning the startup check.
Blocking findings: deployment/templates/_helpers.tpl:217, deployment/templates/_helpers.tpl:217, cloud_registry/ga4gh/registry/service.py:623, deployment/templates/_helpers.tpl:217, cloud_registry/gunicorn_config.py:25, and 4 more
`cloud_registry.gunicorn.extraArgs` could override options that the chart computes or the app requires: `--bind`/`-b` (the Service, container port and probes use port 8080), `--preload` (workers would inherit MongoDB clients created before forking) and `--graceful-timeout` (the termination grace period is derived from `gracefulTimeout`). Rendering now fails for them, matched as Gunicorn parses them: long options also abbreviated (e.g., `--bin`, `--pre`) and as `--option=value`, and `-b` also with an attached value and after the flags `-D` and `-R`. Items that Gunicorn takes as values (e.g., `--bind %(h)s`, with a space) pass. Also note in the Compose file that `--bind` in the host's `GUNICORN_CMD_ARGS` would break the published port, and in the chart's docs that slow uploads through OpenShift Routes, which don't buffer request bodies, hold Gunicorn threads. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Usage section said that the app listens on `server.port` of the config, which now sets the port of the development server only; the image's Gunicorn listens on port 8080 (its `bind` setting), so changing `server.port` doesn't move the image's traffic. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check that `create_app()` adds the expected key (`service_key()`) to a service registered without one, not just any value. Closes #116 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
The image, Docker Compose and the Helm chart now serve the app with Gunicorn instead of Flask's development server. The issue is #116 (pre-release review finding).
create_app(). Gunicorn loadscloud_registry.app:create_app()without--preload, so the MongoDB clients are created after the fork.python -m cloud_registry.appstill runs the dev server.add_service_keys()when several workers start at once. A worker could see a key another worker had just added and report the service as a duplicate of itself.cloud_registry/gunicorn_config.py, overridable viaGUNICORN_CMD_ARGS):/dev/shm, or/tmp, for the read-only root filesystem.cloud_registry.gunicornvalues with schema entries, rendered intoGUNICORN_CMD_ARGS. ApreStopsleep (preStopSleepSeconds, default 5) keeps the pod serving until the endpoints are updated.terminationGracePeriodSecondsis preStop + graceful timeout + 10 s.GUNICORN_CMD_ARGSthrough and waits 30 s on stop (stop_grace_period).gunicorn>=26.2.0,<27.server.host/server.portonly apply to the dev server.Closes #116
Verification
coverage run --source=cloud_registry -m pytest: 614 passed, 100 % coverageruff check,ruff format --check,mypy, semgrep (repo rules),ast-grep scanandast-grep test: passhelm lint --strict(both CI variants) andhelm template: pass. The chart tests parse the renderedGUNICORN_CMD_ARGSwith Gunicorn's own parser and check that the ports match the bind port.docker exec, thendocker stop -t 30, with an idle keep-alive connection open: all requests during the 5 s delay returned 200. Shutdown took 25.5 s, within the 35 s grace period, with no SIGKILL./tmpas tmpfs works, with the heartbeat in/dev/shm, and so does the fallback to/tmp.pre-commit run(its hook repos can't be fetched through the sandbox proxy). The same tools ran directly, except gitleaks.CI: all checks pass (tests on Python 3.10 and 3.12, Helm chart, Compose, static analysis, codecov, Read the Docs).
Notes for deployers
Gunicorn's threads read requests themselves. Slow clients can therefore tie them up unless a proxy that buffers requests sits in front, as ingress-nginx does by default. OpenShift Routes (HAProxy) don't buffer request bodies by default, so slow uploads reach the app directly there.
Declined review findings
The Gunicorn defaults appear in both
gunicorn_config.pyand the Helm values. A test guards against drift.The worker tmp dir helper (
/dev/shmwith a fallback to/tmp) stays, so that the image also works where/dev/shmisn't writable.Sourcery: backfill races with older app versions writing keyless services. The redeploy uses an empty database, and no older version runs against it.
Sourcery: the liveness probe shares the request threads. It has to go through the worker to say anything about it, and the requests are short.
Sourcery: slow uploads without a buffering proxy. This is documented, and bounding reads would need an async server.
Open questions
None.
🤖 Generated with Claude Code