Skip to content
Merged
12 changes: 11 additions & 1 deletion .github/workflows/anyway-dfc2.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
name: dfc2 anyway CI
on:
push:
# only deploy from main: a push to any other branch must never deploy to the servers
branches:
- main
paths:
- '.github/workflows/anyway-dfc2.yml'
- 'apps-dfc2/anyway/**'
workflow_dispatch:


# one deploy at a time per server: two pushes in a row must not run deploy_app concurrently
concurrency:
group: deploy-anyway-dfc2
cancel-in-progress: false

jobs:
anyway:
# only ever deploy main, also for manual runs ("Run workflow" on another branch does nothing)
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-22.04
steps:
- env:
Expand Down
12 changes: 11 additions & 1 deletion .github/workflows/anyway.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
name: anyway CI
on:
push:
# only deploy from main: a push to any other branch must never deploy to the servers
branches:
- main
paths:
- '.github/workflows/anyway.yml'
- 'apps/anyway/**'
workflow_dispatch:


# one deploy at a time per server: two pushes in a row must not run deploy_app concurrently
concurrency:
group: deploy-anyway-dfc
cancel-in-progress: false

jobs:
anyway:
# only ever deploy main, also for manual runs ("Run workflow" on another branch does nothing)
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-22.04
steps:
- env:
Expand Down
69 changes: 69 additions & 0 deletions .github/workflows/thin-db-dumps.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
name: Thin DB dumps

# One-time / occasional cleanup: keep only one anyway DB dump per month in the S3 dump buckets.
# See bin/thin_db_dumps.py. Runs as a dry run unless "delete" is checked.

on:
workflow_dispatch:
inputs:
delete:
description: Really delete (unchecked = dry run, only print what would be deleted)
required: true
type: boolean
default: false
keep_recent_days:
description: Never delete dumps from the last N days (minimum 1)
required: true
type: number
default: 30

permissions:
contents: read

# never run two cleanups at the same time
concurrency:
group: thin-db-dumps
cancel-in-progress: false

jobs:
thin:
runs-on: ubuntu-22.04
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Thin DB dumps
env:
VAULT_CLI_VERSION: "1.10.4"
VAULT_ADDR: ${{ secrets.VAULT_ADDR }}
VAULT_ROLE_ID: ${{ secrets.VAULT_ROLE_ID }}
VAULT_SECRET_ID: ${{ secrets.VAULT_SECRET_ID }}
DELETE: ${{ inputs.delete }}
KEEP_RECENT_DAYS: ${{ inputs.keep_recent_days }}
run: |
set -euo pipefail

if ! [[ "$KEEP_RECENT_DAYS" =~ ^[0-9]+$ ]] || [ "$KEEP_RECENT_DAYS" -lt 1 ]; then
echo "keep_recent_days must be a whole number of at least 1, got: $KEEP_RECENT_DAYS"
exit 1
fi

curl -fsSL https://raw.githubusercontent.com/OriHoch/uumpa-ci-toolbox/ad10e0f8f4bf0ab7ba04d777ee51dc49444d1c04/bin/github_actions_install.sh \
| bash -s ad10e0f8f4bf0ab7ba04d777ee51dc49444d1c04 OriHoch/uumpa-ci-toolbox

uci vault install --version "$VAULT_CLI_VERSION"
export VAULT_TOKEN="$(uci vault approle-login "$VAULT_ROLE_ID" "$VAULT_SECRET_ID")"

export AWS_ACCESS_KEY_ID="$(vault kv get -field=access_key_id kv/projects/anyway/prod/aws_prod_app_user)"
export AWS_SECRET_ACCESS_KEY="$(vault kv get -field=secret_access_key kv/projects/anyway/prod/aws_prod_app_user)"
export AWS_DEFAULT_REGION=eu-central-1

echo "::add-mask::$AWS_ACCESS_KEY_ID"
echo "::add-mask::$AWS_SECRET_ACCESS_KEY"

ARGS=(--keep-recent-days "$KEEP_RECENT_DAYS")
if [ "$DELETE" == "true" ]; then
ARGS+=(--delete)
fi
python3 bin/thin_db_dumps.py "${ARGS[@]}"
2 changes: 1 addition & 1 deletion apps-dfc2/anyway/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ services:

db-backup-cronjob:
x-cronjob:
schedule: "10 0 * * *"
schedule: "10 0 1 * *" # monthly, 1st of the month at 00:10 server time
networks: [dfc]
image: ${PIN_DB_BACKUP_IMAGE:-ghcr.io/hasadna/anyway/db_backup:latest}
environment:
Expand Down
2 changes: 1 addition & 1 deletion apps/anyway/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ services:

db-backup-cronjob:
x-cronjob:
schedule: "10 0 * * *"
schedule: "10 0 1 * *" # monthly, 1st of the month at 00:10 server time
networks: [dfc]
image: ${PIN_DB_BACKUP_IMAGE:-ghcr.io/hasadna/anyway/db_backup:latest}
environment:
Expand Down
228 changes: 228 additions & 0 deletions bin/thin_db_dumps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
#!/usr/bin/env python3
"""One-time cleanup: keep only one DB dump per month in the anyway DB dump buckets.

DB dumps used to be created daily. Now that they are created monthly (and S3 lifecycle
rules expire dumps older than 1 year), this script removes the extra daily dumps.

Dump keys look like YYYY-MM-DD_<series>, e.g.:
2026-11-01_anyway.pgdump.gz (full dump)
2026-11-01_anyway_partial.pgdump.gz (partial dump...)
2026-11-01_anyway_partial_schema.pgdump.gz (...and its matching schema dump)
2026-11-01_testing_anyway_partial.pgdump.gz (a different series, with a file prefix)

Each series is handled separately. A partial dump and its _partial_schema dump are one series,
and a date only counts as complete for that series if all its parts exist and are non-empty
(at least MIN_DUMP_SIZE bytes - a gzipped empty file is still a few dozen bytes).
For each bucket, series and month, the script keeps the earliest complete date and deletes the
other dates. If no date that month is complete, it keeps the date with the most non-empty parts
(preferring one with a non-empty main part, then the earliest); if every date that month is
empty, it keeps the whole month. Either way it prints a warning.

It never touches:
- files whose names don't start with a YYYY-MM-DD_ date
- dumps from the last --keep-recent-days days (default 30, minimum 1)

On a versioned bucket, deleting only adds delete markers; the space is freed once the
noncurrent-version lifecycle rule (modules/anyway/aws_s3_buckets.tf) removes the old versions.

Uses the AWS CLI, with credentials that can list and delete objects in the buckets.

Usage:
bin/thin_db_dumps.py # dry run: print what would be kept / deleted
bin/thin_db_dumps.py --verbose # dry run, listing every file
bin/thin_db_dumps.py --delete # really delete
bin/thin_db_dumps.py --bucket NAME # only one bucket (can be repeated)
"""
import os
import re
import sys
import json
import argparse
import datetime
import tempfile
import subprocess


BUCKETS = [
'dfc-anyway-full-db-dumps',
'dfc-anyway-partial-db-dumps',
'dfc2-anyway-full-db-dumps',
'dfc2-anyway-partial-db-dumps',
]
DATED_KEY_RE = re.compile(r'^(\d{4})-(\d{2})-(\d{2})_(.+)$')
SCHEMA_PART = '_partial_schema.'
PARTIAL_PART = '_partial.'
DELETE_BATCH_SIZE = 1000
MIN_DUMP_SIZE = 1024


class AwsError(Exception):
pass


def aws(*args):
try:
return subprocess.run(
['aws', *args, '--output', 'json'],
check=True, capture_output=True, text=True,
).stdout
except subprocess.CalledProcessError as e:
raise AwsError(f'aws {" ".join(args[:2])} failed (exit code {e.returncode}): {(e.stderr or "").strip()}')


def list_objects(bucket):
# the AWS CLI paginates list-objects-v2 automatically and returns one merged result
out = aws('s3api', 'list-objects-v2', '--bucket', bucket)
return (json.loads(out).get('Contents') or []) if out.strip() else []


def get_versioning_status(bucket):
out = aws('s3api', 'get-bucket-versioning', '--bucket', bucket)
return (json.loads(out).get('Status') or 'Disabled') if out.strip() else 'Disabled'


def parse_key(key):
"""returns (date, series, part) for a dated dump key, or None for any other key

series groups a partial dump with its _partial_schema dump, part tells them apart"""
m = DATED_KEY_RE.match(key)
if not m:
return None
try:
dump_date = datetime.date(int(m[1]), int(m[2]), int(m[3]))
except ValueError:
return None
name = m[4]
if SCHEMA_PART in name:
return dump_date, name.replace(SCHEMA_PART, PARTIAL_PART, 1), 'schema'
return dump_date, name, 'main'


def plan_bucket(bucket, cutoff_date):
# series -> month -> date -> list of objects
tree = {}
series_parts = {}
for obj in list_objects(bucket):
parsed = parse_key(obj['Key'])
if not parsed:
continue
dump_date, series, part = parsed
obj['_part'] = part
tree.setdefault(series, {}).setdefault((dump_date.year, dump_date.month), {}).setdefault(dump_date, []).append(obj)
series_parts.setdefault(series, set()).add(part)
keep, delete, warnings, summary = [], [], [], []
for series, months in sorted(tree.items()):
expected_parts = series_parts[series]
incomplete_months, whole_months = [], []
for month, dates in sorted(months.items()):
month_str = f'{month[0]}-{month[1]:02d}'

def good_parts(dump_date):
return {o['_part'] for o in dates[dump_date] if o['Size'] >= MIN_DUMP_SIZE}

complete_dates = [d for d in sorted(dates) if good_parts(d) == expected_parts]
if complete_dates:
keep_dates = {complete_dates[0]}
else:
# no complete dump this month: keep the best one, never an all-empty one
best = max(sorted(dates), key=lambda d: (len(good_parts(d)), 'main' in good_parts(d), -d.toordinal()))
if good_parts(best):
keep_dates = {best}
incomplete_months.append(f'{month_str} (kept {best})')
else:
keep_dates = set(dates)
whole_months.append(month_str)
for dump_date, objs in dates.items():
if dump_date in keep_dates or dump_date >= cutoff_date:
keep.extend(objs)
else:
delete.extend(objs)
summary.append(f'{series}: {len(months)} months')
if incomplete_months:
warnings.append(f'{series}: no complete dump in {len(incomplete_months)} months, kept the most complete '
f'one: {", ".join(incomplete_months)}')
if whole_months:
warnings.append(f'{series}: only empty dumps in {len(whole_months)} months, kept all of them: '
f'{", ".join(whole_months)}')
return keep, delete, warnings, summary


def delete_objects(bucket, objs):
for i in range(0, len(objs), DELETE_BATCH_SIZE):
batch_objs = objs[i:i + DELETE_BATCH_SIZE]
batch = {'Objects': [{'Key': o['Key']} for o in batch_objs], 'Quiet': True}
with tempfile.NamedTemporaryFile('w', suffix='.json', delete=False) as f:
json.dump(batch, f)
batch_file = f.name
try:
out = aws('s3api', 'delete-objects', '--bucket', bucket, '--delete', f'file://{batch_file}')
except AwsError as e:
raise AwsError(f'delete batch {i // DELETE_BATCH_SIZE + 1} '
f'({batch_objs[0]["Key"]} .. {batch_objs[-1]["Key"]}): {e}')
finally:
os.unlink(batch_file)
errors = (json.loads(out).get('Errors') or []) if out.strip() else []
for e in errors:
print(f' ERROR deleting {e.get("Key")}: {e.get("Code")} {e.get("Message")}')
if errors:
raise Exception(f'failed to delete {len(errors)} objects from {bucket} '
f'in batch {i // DELETE_BATCH_SIZE + 1}')
print(f' deleted batch {i // DELETE_BATCH_SIZE + 1}: {len(batch_objs)} files')


def human_size(num_bytes):
return f'{num_bytes / 1024 ** 3:.1f} GB'


def positive_int(value):
value = int(value)
if value < 1:
raise argparse.ArgumentTypeError('must be at least 1')
return value


def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--delete', action='store_true', help='really delete (default is a dry run)')
parser.add_argument('--bucket', action='append', help='bucket to process (default: all dump buckets)')
parser.add_argument('--keep-recent-days', type=positive_int, default=30,
help='never delete dumps from the last N days (default 30, minimum 1)')
parser.add_argument('--verbose', action='store_true', help='list every kept / deleted file')
args = parser.parse_args()
cutoff_date = datetime.date.today() - datetime.timedelta(days=args.keep_recent_days)
print(f'{"DELETING" if args.delete else "DRY RUN"}: keeping 1 complete dump per series per month, '
f'and everything from {cutoff_date} onwards')
total_deleted_bytes = 0
for bucket in args.bucket or BUCKETS:
versioning = get_versioning_status(bucket)
keep, delete, warnings, summary = plan_bucket(bucket, cutoff_date)
deleted_bytes = sum(o['Size'] for o in delete)
total_deleted_bytes += deleted_bytes
print(f'\n{bucket} (versioning: {versioning}): keep {len(keep)} files ({human_size(sum(o["Size"] for o in keep))}), '
f'delete {len(delete)} files ({human_size(deleted_bytes)})')
if versioning != 'Disabled':
print(' NOTE: versioned bucket - deleted files stay as noncurrent versions (still billed) '
'until the noncurrent-version lifecycle rule removes them')
for line in summary:
print(f' series {line}')
for line in warnings:
print(f' WARNING: {line}')
if args.verbose:
for o in sorted(keep, key=lambda o: o['Key']):
print(f' keep {o["Key"]}')
for o in sorted(delete, key=lambda o: o['Key']):
print(f' delete {o["Key"]}')
if args.delete and delete:
delete_objects(bucket, delete)
print(f' deleted {len(delete)} files')
print(f'\nTotal {"deleted" if args.delete else "to delete"}: {human_size(total_deleted_bytes)}')
if not args.delete:
print('Dry run only, run again with --delete to really delete')


if __name__ == '__main__':
try:
sys.exit(main())
except AwsError as e:
print(f'\nERROR: {e}')
sys.exit(1)
5 changes: 5 additions & 0 deletions modules/anyway/aws_db_dumps_users.tf
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,10 @@ EOF

resource "aws_iam_user" "dfc2_db_dumps_reader" {
name = "dfc2-anyway-db-dumps-reader"
lifecycle {
# its tags were added by hand in AWS (a note about whose access keys these are); keep them
ignore_changes = [tags, tags_all]
}
}

resource "null_resource" "dfc2_aws_db_dumps_reader_keys_vault" {
Expand All @@ -185,6 +189,7 @@ resource "aws_iam_user_policy" "dfc2_db_dumps_reader" {
"s3:HeadObject"
],
"Resource": [
"arn:aws:s3:::${aws_s3_bucket.bucket["dfc-anyway-cbs"].id}",
"arn:aws:s3:::${aws_s3_bucket.bucket["dfc2-anyway-full-db-dumps"].id}",
"arn:aws:s3:::${aws_s3_bucket.bucket["dfc2-anyway-full-db-dumps"].id}/*",
"arn:aws:s3:::${aws_s3_bucket.bucket["dfc2-anyway-partial-db-dumps"].id}",
Expand Down
Loading