Skip to content

About

Cloud function definition for a database replication service

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

Database replication service (db-replicator)

Scheduled logical export of one Cloud SQL database to a Cloud Storage bucket. It runs as a Cloud Run function (2nd gen) triggered by Pub/Sub.

Cloud Scheduler job → Pub/Sub topic → Eventarc trigger (push, OIDC, internal ingress)
  → this function (python314) → Cloud SQL Admin API instances.export
  → gs://BUCKET/DATABASE/<event time>-<event id>.sql.gz

Upgrading from the 2024 version (python39)? That version's setup steps granted the function's service account Service Account Token Creator and Cloud Pub/Sub Service Agent.

Each of those lets the account impersonate every service account in the project. Neither is needed. Remove them, along with Cloud SQL Viewer and any project-wide Cloud Run Invoker. Then follow Least-privilege setup.

The old code also exported only the database named in its source, postgres. Check that EXPORT_DATABASE names your application's database.

Configuration

Variable Meaning
EXPORT_PROJECT Project of the Cloud SQL instance
EXPORT_INSTANCE Cloud SQL instance id
EXPORT_DATABASE The one database to export. For Postgres, this is your app's database, not the default postgres.
EXPORT_BUCKET Destination bucket (name only, no gs://)
EXPORT_POLL_TIMEOUT_SECONDS Optional, default 480. Keep it under the function timeout (540 s).

Behaviour

  • The Pub/Sub message body is ignored. The variables above fix what gets exported, so a publisher cannot redirect it.

  • Object names come from the event's time and id. A redelivered message targets the same object. Cloud SQL fails an export whose file already exists, so a redelivery never writes a second copy.

  • The function waits for the export operation. Cloud SQL accepts an export request even when the operation later fails.

  • Each run writes structured JSON log lines with component: db-replicator:

    message severity
    EXPORT_STARTED INFO
    EXPORT_SUCCEEDED INFO
    EXPORT_STILL_RUNNING WARNING
    EXPORT_FAILED ERROR

    An EXPORT_FAILED line carries the cause in its error field.

  • Failures are reported through logs, not the HTTP status. The function returns normally either way. Returning an error would make Pub/Sub redeliver the message with backoff for a day, repeating the failure. The alert policy (below) is what makes failures visible.

Least-privilege setup

Replace the upper-case placeholders.

PROJECT_ID=...; REGION=us-west1; INSTANCE=...; DATABASE=...; BUCKET=...
SA_NAME=...; TOPIC=...; JOB=...; SERVICE=...
SA=$SA_NAME@$PROJECT_ID.iam.gserviceaccount.com

# Runtime and trigger identity: export only. No token roles, no service-agent roles.
gcloud iam service-accounts create $SA_NAME --project=$PROJECT_ID \
  --display-name="db-replicator (Cloud SQL export only)"
gcloud iam roles create sqlExportRunner --project=$PROJECT_ID \
  --title="Cloud SQL export runner" \
  --permissions=cloudsql.instances.export,cloudsql.instances.get
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:$SA" \
  --role="projects/$PROJECT_ID/roles/sqlExportRunner"

# Bucket: no public access, no project-Viewer read, retention by lifecycle.
gcloud storage buckets create gs://$BUCKET --project=$PROJECT_ID --location=$REGION \
  --uniform-bucket-level-access --public-access-prevention
printf '{"rule":[{"action":{"type":"Delete"},"condition":{"age":35}}]}' > /tmp/lifecycle.json
gcloud storage buckets update gs://$BUCKET --lifecycle-file=/tmp/lifecycle.json

# The Cloud SQL instance's own service agent writes the export file.
SQL_SA=$(gcloud sql instances describe $INSTANCE --project=$PROJECT_ID --format="value(serviceAccountEmailAddress)")
gcloud storage buckets add-iam-policy-binding gs://$BUCKET \
  --member="serviceAccount:$SQL_SA" --role=roles/storage.objectCreator

gcloud pubsub topics create $TOPIC --project=$PROJECT_ID

Then deploy, and let the trigger identity invoke this service only:

gcloud run services add-iam-policy-binding $SERVICE --region=$REGION --project=$PROJECT_ID \
  --member="serviceAccount:$SA" --role=roles/run.invoker
gcloud scheduler jobs create pubsub $JOB --location=$REGION --project=$PROJECT_ID \
  --schedule="0 3 * * 0" --time-zone="America/Los_Angeles" --topic=$TOPIC --message-body='{}'

The push's OIDC token is minted by Google's own Pub/Sub service agent. Do not grant token or service-agent roles to the function's service account.

Buckets created before uniform bucket-level access may still carry legacy projectViewer read bindings. Remove those, because the dumps contain your database.

Deploy

Run this from the repository root. Pass both service-account flags and the ingress flag every time: per the gcloud help, an omitted service-account flag falls back to the Compute Engine default service account.

: "${PROJECT_ID:?}" "${SA:?}" "${SERVICE:?}" "${TOPIC:?}" "${INSTANCE:?}" "${DATABASE:?}" "${BUCKET:?}"
gcloud functions deploy $SERVICE \
  --project=$PROJECT_ID --region=$REGION --gen2 \
  --runtime=python314 --entry-point=main --source=. \
  --trigger-topic=$TOPIC \
  --trigger-service-account=$SA --run-service-account=$SA \
  --ingress-settings=internal-only --no-allow-unauthenticated \
  --runtime-update-policy=automatic \
  --max-instances=1 --memory=256Mi --timeout=540s \
  --set-env-vars=EXPORT_PROJECT=$PROJECT_ID,EXPORT_INSTANCE=$INSTANCE,EXPORT_DATABASE=$DATABASE,EXPORT_BUCKET=$BUCKET

The deployer needs Cloud Functions Developer, plus Service Account User on $SA and on the Cloud Build service account. .gcloudignore keeps tests, tooling and local environments out of the upload.

Alerting

ops/create_alert_policy.py creates one email notification channel per recipient and a single log-match alert policy. Re-running it reuses existing channels and leaves an existing policy alone. It needs Monitoring Editor.

The policy fires on any of:

  • this function's WARNING-or-worse lines;
  • a Pub/Sub push rejected before the code ran;
  • a failed scheduler attempt.
python3 ops/create_alert_policy.py --project=$PROJECT_ID --service=$SERVICE --scheduler-job=$JOB \
  [email protected] [email protected] --dry-run   # shows the payloads only
python3 ops/create_alert_policy.py --project=$PROJECT_ID --service=$SERVICE --scheduler-job=$JOB \
  [email protected] [email protected]

Test locally

Nothing calls Google Cloud; Cloud SQL is faked.

uv venv --python 3.14 .venv
uv pip install --python .venv/bin/python --require-hashes -r requirements.txt   # same pins as the deploy
uv pip install --python .venv/bin/python pytest
.venv/bin/python -m pytest                                    # unit tests
uvx ruff check . && uvx ruff format --check .                 # lint and format
uvx pip-audit -r requirements.txt --require-hashes --disable-pip    # known vulnerabilities
tests/smoke_test.sh .venv/bin                                 # real functions-framework + gunicorn server

Update dependencies

Edit requirements.in, regenerate the hash-locked file, then rerun everything above:

uv pip compile requirements.in --python-version 3.14 \
  --python-platform x86_64-manylinux_2_28 --generate-hashes -o requirements.txt

Operate

gcloud scheduler jobs run $JOB --location=$REGION --project=$PROJECT_ID          # export now
gcloud logging read "resource.type=\"cloud_run_revision\" AND resource.labels.service_name=\"$SERVICE\"
  AND jsonPayload.component=\"db-replicator\"" --project=$PROJECT_ID --freshness=1d \
  --format="value(timestamp,severity,jsonPayload.message,jsonPayload.uri,jsonPayload.error)"
gcloud storage ls -l gs://$BUCKET/$DATABASE/    # newest object should be a real size, not a few KB

Restore test (quarterly). Import a dump into a scratch database on the same instance, check it, then drop it. Never import over the live database, and never into a less protected environment.

gcloud sql databases create restore_check --instance=$INSTANCE --project=$PROJECT_ID
gcloud sql import sql $INSTANCE gs://$BUCKET/$DATABASE/<file>.sql.gz --database=restore_check --project=$PROJECT_ID
gcloud sql databases delete restore_check --instance=$INSTANCE --project=$PROJECT_ID

Cloud SQL runs one operation at a time per instance. An export that overlaps a backup fails with "operation in progress". That failure is logged as EXPORT_FAILED and alerted on. Run the job again.

About

Cloud function definition for a database replication service

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages