Repository Public
1#!/usr/bin/env bash2# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project : SPIDER8# File : scripts/drain.sh9# Module : Scripts10# Repository : https://git.spboucher.ai/spider11# Project Website : Not specified12# Created : 2026-12-0413# Last Modified : 2026-12-0414#15# Author : Simon-Pierre Boucher16# Position : Professor of Finance17# Institution : Université du Québec en Outaouais (UQO)18# Organization : SP Boucher19# Website : https://spboucher.ai20# Git : https://git.spboucher.ai21#22# Preferred Contact: contact@spboucher.ai23# Development : dev@spboucher.ai24# Support : support@spboucher.ai25# Security/Admin : admin@spboucher.ai26#27# Copyright (c) 202628# Simon-Pierre Boucher29# All rights reserved where applicable. This file is governed by the30# applicable project license, copyright notices and relevant law.31# Existing third-party rights and notices remain unaffected.32#33# License : ISC34#35# Do not embed credentials, private keys, access tokens,36# certificates or confidential personal information.37#38# =============================================================================39# END OF SP BOUCHER SOURCE HEADER40# =============================================================================4142# Drain every worker (no new lease), wait until no task is leased, then exit 0. Use before an update.43# Usage: SPIDER_URL=… SPIDER_API_KEY=<admin key> scripts/drain.sh [--resume] [--timeout 600]44set -euo pipefail45URL="${SPIDER_URL:-http://127.0.0.1:8900}"; KEY="${SPIDER_API_KEY:?}"; RESUME=false; TIMEOUT=60046while [ $# -gt 0 ]; do case "$1" in --resume) RESUME=true; shift ;; --timeout) TIMEOUT="$2"; shift 2 ;; *) exit 2 ;; esac; done47api() { curl -fsS --max-time 20 -H "Authorization: Bearer $KEY" "$@"; }48for id in $(api "$URL/v1/workers" | python3 -c 'import json,sys; [print(w["worker_id"]) for w in json.load(sys.stdin)["items"] if w["state"]!="offline"]'); do49 api -X POST "$URL/v1/workers/$id/drain?resume=$RESUME" >/dev/null; echo "worker $id: $([ $RESUME = true ] && echo resumed || echo draining)"50done51$RESUME && exit 052END=$(( $(date +%s) + TIMEOUT ))53while :; do54 N="$(api "$URL/v1/workers" | python3 -c 'import json,sys; print(sum(w["leased"] for w in json.load(sys.stdin)["items"]))')"55 [ "$N" = 0 ] && { echo "drained: no task in flight"; exit 0; }56 [ "$(date +%s)" -ge "$END" ] && { echo "timeout: $N task(s) still leased" >&2; exit 1; }57 sleep 358done59