banger/stop.sh

60 lines
1.3 KiB
Bash
Executable file

#!/usr/bin/env bash
set -euo pipefail
log() {
printf '[stop] %s\n' "$*"
}
usage() {
cat <<'EOF'
Usage: ./stop.sh <id-or-name-prefix>
Sends Ctrl+Alt+Del to the guest via the Firecracker API socket.
EOF
}
find_vm_json() {
local query="$1"
local vm_json match_count=0 match=""
for vm_json in state/vms/*/vm.json; do
[[ -f "$vm_json" ]] || continue
local id name
id="$(jq -r '.meta.id // empty' "$vm_json")"
name="$(jq -r '.meta.name // empty' "$vm_json")"
if [[ "$id" == "$query"* || "$name" == "$query"* ]]; then
match="$vm_json"
match_count=$((match_count + 1))
fi
done
if (( match_count == 0 )); then
log "no VM found for prefix: $query"
exit 1
fi
if (( match_count > 1 )); then
log "multiple VMs found for prefix: $query"
exit 1
fi
printf '%s' "$match"
}
QUERY="${1:-}"
if [[ -z "$QUERY" || "$QUERY" == "-h" || "$QUERY" == "--help" ]]; then
usage
exit 1
fi
VM_JSON="$(find_vm_json "$QUERY")"
API_SOCK="$(jq -r '.meta.api_sock // empty' "$VM_JSON")"
if [[ -z "$API_SOCK" || ! -S "$API_SOCK" ]]; then
log "api socket not found: $API_SOCK"
exit 1
fi
log "sending Ctrl+Alt+Del to guest"
sudo -E curl --unix-socket "$API_SOCK" -X PUT http://localhost/actions \
-H "Content-Type: application/json" \
-d '{ "action_type": "SendCtrlAltDel" }' >/dev/null
log "requested shutdown"