@@ -15,6 +15,9 @@ TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
1515K8S_API_URL=https://$KUBERNETES_SERVICE_HOST :$KUBERNETES_SERVICE_PORT /api/v1
1616CERT=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
1717
18+ LOGICAL_BACKUP_PROVIDER=${LOGICAL_BACKUP_PROVIDER:= " s3" }
19+ LOGICAL_BACKUP_S3_RETENTION_TIME=${LOGICAL_BACKUP_S3_RETENTION_TIME:= " " }
20+
1821function estimate_size {
1922 " $PG_BIN " /psql -tqAc " ${ALL_DB_SIZE_QUERY} "
2023}
@@ -28,6 +31,57 @@ function compress {
2831 pigz
2932}
3033
34+ function aws_delete_objects {
35+ args=(
36+ " --bucket=$LOGICAL_BACKUP_S3_BUCKET "
37+ )
38+
39+ [[ ! -z " $LOGICAL_BACKUP_S3_ENDPOINT " ]] && args+=(" --endpoint-url=$LOGICAL_BACKUP_S3_ENDPOINT " )
40+ [[ ! -z " $LOGICAL_BACKUP_S3_REGION " ]] && args+=(" --region=$LOGICAL_BACKUP_S3_REGION " )
41+
42+ aws s3api delete-objects " ${args[@]} " --delete Objects=[" $( printf {Key=%q}, " $@ " ) " ],Quiet=true
43+ }
44+ export -f aws_delete_objects
45+
46+ function aws_delete_outdated {
47+ if [[ -z " $LOGICAL_BACKUP_S3_RETENTION_TIME " ]] ; then
48+ echo " no retention time configured: skip cleanup of outdated backups"
49+ return 0
50+ fi
51+
52+ # define cutoff date for outdated backups (day precision)
53+ cutoff_date=$( date -d " $LOGICAL_BACKUP_S3_RETENTION_TIME ago" +%F)
54+
55+ # mimic bucket setup from Spilo
56+ prefix=" spilo/" $SCOPE$LOGICAL_BACKUP_S3_BUCKET_SCOPE_SUFFIX " /logical_backups/"
57+
58+ args=(
59+ " --no-paginate"
60+ " --output=text"
61+ " --prefix=$prefix "
62+ " --bucket=$LOGICAL_BACKUP_S3_BUCKET "
63+ )
64+
65+ [[ ! -z " $LOGICAL_BACKUP_S3_ENDPOINT " ]] && args+=(" --endpoint-url=$LOGICAL_BACKUP_S3_ENDPOINT " )
66+ [[ ! -z " $LOGICAL_BACKUP_S3_REGION " ]] && args+=(" --region=$LOGICAL_BACKUP_S3_REGION " )
67+
68+ # list objects older than the cutoff date
69+ aws s3api list-objects " ${args[@]} " --query=" Contents[?LastModified<='$cutoff_date '].[Key]" > /tmp/outdated-backups
70+
71+ # spare the last backup
72+ sed -i ' $d' /tmp/outdated-backups
73+
74+ count=$( wc -l < /tmp/outdated-backups)
75+ if [[ $count == 0 ]] ; then
76+ echo " no outdated backups to delete"
77+ return 0
78+ fi
79+ echo " deleting $count outdated backups created before $cutoff_date "
80+
81+ # deleted outdated files in batches with 100 at a time
82+ tr ' \n' ' \0' < /tmp/outdated-backups | xargs -0 -P1 -n100 bash -c ' aws_delete_objects "$@"' _
83+ }
84+
3185function aws_upload {
3286 declare -r EXPECTED_SIZE=" $1 "
3387
@@ -59,6 +113,7 @@ function upload {
59113 ;;
60114 * )
61115 aws_upload $(( $(estimate_size) / DUMP_SIZE_COEFF))
116+ aws_delete_outdated
62117 ;;
63118 esac
64119}
0 commit comments