infra/clusters/aprs/postgres-cleanup-cronjob.yaml
2025-07-27 11:35:59 -05:00

107 lines
No EOL
3.1 KiB
YAML

apiVersion: batch/v1
kind: CronJob
metadata:
name: postgres-cleanup
namespace: aprs
spec:
schedule: "*/15 * * * *" # Every 15 minutes
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
template:
spec:
restartPolicy: OnFailure
containers:
- name: postgres-cleanup
image: postgres:17-alpine
env:
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: postgis-secret
key: postgres-password
- name: PGHOST
value: postgis
- name: PGUSER
value: aprs
- name: PGDATABASE
value: aprs_prod
command:
- /bin/sh
- -c
- |
echo "Starting PostgreSQL connection cleanup..."
# Kill idle connections older than 30 minutes
psql -c "
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'aprs_prod'
AND pid <> pg_backend_pid()
AND state = 'idle'
AND state_change < NOW() - INTERVAL '30 minutes';"
# Kill idle in transaction connections older than 5 minutes
psql -c "
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'aprs_prod'
AND pid <> pg_backend_pid()
AND state = 'idle in transaction'
AND state_change < NOW() - INTERVAL '5 minutes';"
# Log connection stats
psql -c "
SELECT
state,
COUNT(*) as count,
MAX(NOW() - state_change) as max_duration
FROM pg_stat_activity
WHERE datname = 'aprs_prod'
GROUP BY state
ORDER BY count DESC;"
# Check total connections vs max
psql -c "
SELECT
(SELECT COUNT(*) FROM pg_stat_activity) as current_connections,
(SELECT setting::int FROM pg_settings WHERE name = 'max_connections') as max_connections,
ROUND(100.0 * COUNT(*) / (SELECT setting::int FROM pg_settings WHERE name = 'max_connections'), 2) as percentage_used
FROM pg_stat_activity;"
echo "Cleanup completed successfully"
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: postgres-cleanup
namespace: aprs
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: postgres-cleanup
namespace: aprs
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: postgres-cleanup
namespace: aprs
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: postgres-cleanup
subjects:
- kind: ServiceAccount
name: postgres-cleanup
namespace: aprs