1#!/bin/sh -e
2
3vmname="$1"
4os_image_id="$2"
5
6if echo "$vmname" | grep -vqE '^(cvm|capsul)-[a-z0-9]{10}$'; then
7 echo "vmname $vmname must match "'"^capsul-[a-z0-9]{10}$"'
8 exit 1
9fi
10
11pidof_command_json='{"path":"/usr/bin/env", "arg":["pidof","acpid"], "capture-output":true}'
12if echo "$os_image_id" | grep -q 'nixos'; then
13 pidof_command_json='{"path":"/run/current-system/sw/bin/pidof", "arg":["acpid"], "capture-output":true}'
14fi
15
16qemuAgentCommandOutput="no-guest-agent-socket"
17if virsh dumpxml "$vmname" | grep -q guest_agent ; then
18 qemuAgentCommandOutput="$( { virsh qemu-agent-command "$vmname" --cmd '{"execute": "guest-info"}' || printf '%s' 'no-qemu-guest-agent'; } | tr -d '\n' )"
19 if [ "$qemuAgentCommandOutput" != "no-qemu-guest-agent" ] ; then
20 isAcpidRunning='{"execute": "guest-exec", "arguments":'"$pidof_command_json}"
21 qemuAgentCommandOutput="$( { virsh qemu-agent-command "$vmname" --cmd "$isAcpidRunning" || printf '%s' 'no-acpid'; } | tr -d '\n' )"
22 if [ "$qemuAgentCommandOutput" != "no-acpid" ] ; then
23 # {"return":{"pid":2967}}
24 pidInsideVm="$(echo "$qemuAgentCommandOutput" | jq -r '.return.pid')"
25 qemuAgentCommandOutput="error"
26 if echo "$pidInsideVm" | grep -vqE '^[0-9]+$'; then
27 echo "pidInsideVm: $pidInsideVm WTF!!?!?"
28 exit 1
29 fi
30 getStatusOfProcessInsideVm='{"execute": "guest-exec-status", "arguments":{"pid":'"$pidInsideVm"'}}'
31 exited='false'
32 tries=0
33 while [ "$exited" = "false" ] && [ "$tries" -lt 10 ] ; do
34 tries=$((tries+1))
35 sleep 0.1
36 processStatusInfo="$( virsh qemu-agent-command "$vmname" --cmd "$getStatusOfProcessInsideVm" )"
37 # {"return":{"exitcode":0,"out-data":"MTgwNAo=","exited":true}}
38 exited="$(echo "$processStatusInfo" | jq -r '.return.exited')"
39 if [ "$exited" = "true" ] ; then
40 exitCode="$(echo "$processStatusInfo" | jq -r '.return.exitcode')"
41 if [ "$exitCode" = "0" ] ; then
42 qemuAgentCommandOutput="ok"
43 else
44 qemuAgentCommandOutput="no-acpid"
45 fi
46 fi
47 done
48 fi
49 fi
50fi
51
52echo "$qemuAgentCommandOutput"