forked from longtao.wu/droboticflow
75 lines
2.1 KiB
Bash
Executable File
75 lines
2.1 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
|
|
K8S_NAMESPACE="${K8S_NAMESPACE:-droboticflow}"
|
|
POC_CLEANUP_MIN_AGE_HOURS="${POC_CLEANUP_MIN_AGE_HOURS:-24}"
|
|
POC_CLEANUP_DRY_RUN="${POC_CLEANUP_DRY_RUN:-true}"
|
|
|
|
if ! [[ "$POC_CLEANUP_MIN_AGE_HOURS" =~ ^[1-9][0-9]*$ ]]; then
|
|
echo "ERROR: POC_CLEANUP_MIN_AGE_HOURS must be a positive integer" >&2
|
|
exit 1
|
|
fi
|
|
|
|
case "$(printf '%s' "$POC_CLEANUP_DRY_RUN" | tr '[:upper:]' '[:lower:]')" in
|
|
true|1|yes|on) dry_run=true ;;
|
|
false|0|no|off) dry_run=false ;;
|
|
*)
|
|
echo "ERROR: POC_CLEANUP_DRY_RUN must be true or false" >&2
|
|
exit 1
|
|
;;
|
|
esac
|
|
|
|
cutoff_epoch="$(python3 - "$POC_CLEANUP_MIN_AGE_HOURS" <<'PY'
|
|
import sys
|
|
import time
|
|
|
|
hours = int(sys.argv[1])
|
|
print(int(time.time() - hours * 3600))
|
|
PY
|
|
)"
|
|
|
|
resources="$(
|
|
kubectl -n "$K8S_NAMESPACE" get pods,jobs -o json | python3 - "$cutoff_epoch" <<'PY'
|
|
import datetime as dt
|
|
import json
|
|
import sys
|
|
|
|
cutoff = int(sys.argv[1])
|
|
payload = json.load(sys.stdin)
|
|
for item in payload.get("items", []):
|
|
kind = item.get("kind", "").lower()
|
|
name = item.get("metadata", {}).get("name", "")
|
|
created = item.get("metadata", {}).get("creationTimestamp", "")
|
|
if not name or kind not in {"pod", "job"}:
|
|
continue
|
|
try:
|
|
created_epoch = int(dt.datetime.fromisoformat(created.replace("Z", "+00:00")).timestamp())
|
|
except ValueError:
|
|
continue
|
|
if created_epoch > cutoff:
|
|
continue
|
|
status = item.get("status", {})
|
|
phase = status.get("phase", "")
|
|
failed = int(status.get("failed") or 0)
|
|
succeeded = int(status.get("succeeded") or 0)
|
|
if kind == "pod" and phase not in {"Failed", "Succeeded"}:
|
|
continue
|
|
if kind == "job" and failed <= 0 and succeeded <= 0:
|
|
continue
|
|
print(f"{kind}/{name}")
|
|
PY
|
|
)"
|
|
|
|
if [[ -z "$resources" ]]; then
|
|
echo "no runtime pod/job artifacts older than ${POC_CLEANUP_MIN_AGE_HOURS}h need cleanup"
|
|
exit 0
|
|
fi
|
|
|
|
printf '%s\n' "$resources"
|
|
if [[ "$dry_run" == "true" ]]; then
|
|
echo "dry-run only; set POC_CLEANUP_DRY_RUN=false to delete these Kubernetes artifacts"
|
|
exit 0
|
|
fi
|
|
|
|
printf '%s\n' "$resources" | xargs -r kubectl -n "$K8S_NAMESPACE" delete --ignore-not-found=true
|