Jobber/scripts/jobber-pipeline-telegram.sh

78 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
# Run Jobber pipeline, wait until it finishes, send summary to Telegram.
# Secrets: copy scripts/jobber-cron.env.example to /root/.jobber-cron.env (chmod 600).
set -euo pipefail
ENV_FILE="${JOBBER_CRON_ENV:-/root/.jobber-cron.env}"
if [[ ! -f "$ENV_FILE" ]]; then
echo "Missing env file: $ENV_FILE (set JOBBER_CRON_ENV or create the default path)" >&2
exit 1
fi
# shellcheck source=/dev/null
source "$ENV_FILE"
: "${TELEGRAM_BOT_TOKEN:?Set TELEGRAM_BOT_TOKEN in $ENV_FILE}"
: "${TELEGRAM_CHAT_ID:?Set TELEGRAM_CHAT_ID in $ENV_FILE}"
BASE="${JOBOPS_URL:-http://127.0.0.1:3005}"
AUTH=()
if [[ -n "${BASIC_AUTH_USER:-}" && -n "${BASIC_AUTH_PASSWORD:-}" ]]; then
AUTH=(-u "${BASIC_AUTH_USER}:${BASIC_AUTH_PASSWORD}")
fi
send_tg() {
local msg="$1"
curl -sS -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-H "Content-Type: application/json" \
-d "$(jq -n --arg c "$TELEGRAM_CHAT_ID" --arg t "$msg" '{chat_id: $c, text: $t}')" >/dev/null
}
fetch_status() {
curl -sS "${AUTH[@]}" "${BASE}/api/pipeline/status"
}
body="$(fetch_status)"
if ! echo "$body" | jq -e '.ok == true' >/dev/null 2>&1; then
send_tg "Jobber: /api/pipeline/status failed (before run). Check container."
exit 1
fi
if echo "$body" | jq -e '.data.isRunning == true' >/dev/null 2>&1; then
send_tg "Jobber: pipeline already running; skipping scheduled run."
exit 0
fi
resp="$(curl -sS "${AUTH[@]}" -X POST "${BASE}/api/pipeline/run" \
-H "Content-Type: application/json" -d '{}')"
if ! echo "$resp" | jq -e '.ok == true' >/dev/null 2>&1; then
send_tg "Jobber: POST /api/pipeline/run failed: $(echo "$resp" | jq -c .)"
exit 1
fi
was_running=0
for _ in $(seq 1 720); do
sleep 30
body="$(fetch_status)"
if ! echo "$body" | jq -e '.ok == true' >/dev/null 2>&1; then
send_tg "Jobber: status check failed mid-run."
exit 1
fi
running="$(echo "$body" | jq -r '.data.isRunning')"
if [[ "$running" == "true" ]]; then
was_running=1
elif [[ "$was_running" -eq 1 ]]; then
lr="$(echo "$body" | jq '.data.lastRun')"
st="$(echo "$lr" | jq -r '.status // "unknown"')"
disc="$(echo "$lr" | jq -r '.jobsDiscovered // 0')"
proc="$(echo "$lr" | jq -r '.jobsProcessed // 0')"
err="$(echo "$lr" | jq -r '.errorMessage // empty')"
msg="Jobber pipeline finished: ${st}. Discovered: ${disc}, processed: ${proc}."
[[ -n "$err" ]] && msg="${msg}"$'\n'"Error: ${err}"
send_tg "$msg"
exit 0
fi
done
send_tg "Jobber: timed out waiting for pipeline (6h). Check server."
exit 1