droboticflow/scripts/cleanup-operator-jobs.sh
eust-w 20b36fe6a0
Some checks are pending
CI / verify (push) Waiting to run
CI / docker-build (push) Waiting to run
🚀 Harden production runtime and acceptance
2026-06-16 14:28:49 +08:00

91 lines
2.8 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DEPLOY_ENV="${DEPLOY_ENV:-}"
if [[ $# -gt 0 && -z "$DEPLOY_ENV" && "${1:-}" != -* ]]; then
DEPLOY_ENV="$1"
shift
fi
export DEPLOY_ENV
# shellcheck source=scripts/load-deploy-env.sh
source "$ROOT_DIR/scripts/load-deploy-env.sh"
K8S_NAMESPACE="${K8S_NAMESPACE:-droboticflow}"
OPERATOR_JOB_CLEANUP_MIN_AGE_SECONDS="${OPERATOR_JOB_CLEANUP_MIN_AGE_SECONDS:-86400}"
OPERATOR_JOB_CLEANUP_STATUSES="${OPERATOR_JOB_CLEANUP_STATUSES:-succeeded,failed}"
DRY_RUN="${DRY_RUN:-false}"
job_names="$(
kubectl -n "$K8S_NAMESPACE" get jobs \
-l app=droboticflow,component=operator-runner \
-o json |
OPERATOR_JOB_CLEANUP_MIN_AGE_SECONDS="$OPERATOR_JOB_CLEANUP_MIN_AGE_SECONDS" \
OPERATOR_JOB_CLEANUP_STATUSES="$OPERATOR_JOB_CLEANUP_STATUSES" \
python3 -c '
import datetime as dt
import json
import os
import sys
min_age_seconds = int(os.environ["OPERATOR_JOB_CLEANUP_MIN_AGE_SECONDS"])
statuses = {item.strip().lower() for item in os.environ["OPERATOR_JOB_CLEANUP_STATUSES"].split(",") if item.strip()}
payload = json.load(sys.stdin)
now = dt.datetime.now(dt.timezone.utc)
def parse_time(value):
if not value:
return None
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
def condition_time(status, condition_type):
for condition in status.get("conditions", []) or []:
if str(condition.get("type", "")).lower() != condition_type:
continue
if str(condition.get("status", "")).lower() != "true":
continue
parsed = parse_time(condition.get("lastTransitionTime"))
if parsed:
return parsed
return None
for item in payload.get("items", []):
status = item.get("status", {})
succeeded = int(status.get("succeeded") or 0)
failed = int(status.get("failed") or 0)
state = ""
if succeeded > 0:
state = "succeeded"
finished_at = parse_time(status.get("completionTime")) or condition_time(status, "complete")
elif failed > 0:
state = "failed"
finished_at = parse_time(status.get("completionTime")) or condition_time(status, "failed")
else:
finished_at = None
if not state or state not in statuses:
continue
if finished_at is None or (now - finished_at).total_seconds() < min_age_seconds:
continue
name = item.get("metadata", {}).get("name", "")
if name:
print(name)
'
)"
if [[ -z "$job_names" ]]; then
echo "No finished operator-runner Jobs matched cleanup filters in namespace $K8S_NAMESPACE."
exit 0
fi
if [[ "$DRY_RUN" == "true" ]]; then
printf '%s\n' "$job_names"
exit 0
fi
while IFS= read -r job_name; do
[[ -z "$job_name" ]] && continue
kubectl -n "$K8S_NAMESPACE" delete job "$job_name"
done <<<"$job_names"