diff --git a/agent.sh b/agent.sh index 5575097..c847469 100644 --- a/agent.sh +++ b/agent.sh @@ -64,19 +64,12 @@ function start_vm { function stop_vm { DEFINE_string 'vm_name' '-' 'VM NAME' 'm' - DEFINE_string 'subnet_name' '-' 'Subnet NAME' 's' DEFINE_boolean 'dryrun' false 'Enable dry-run mode' 'd' FLAGS "$@" || exit $? eval set -- "${FLAGS_ARGV}" - # delete qemu - # check how many qemu in subnet - # if qemu number = 0 - delete_subnet "${FLAGS_subnet_name}" - # check subnet number in vpc - # if subnet number =0 - # delete_vpc "${FLAGS_vpc_name}" + qemu_stop_vm "${FLAGS_vm_name}" } diff --git a/lib/qemu.sh b/lib/qemu.sh index a8fea7e..c79f642 100644 --- a/lib/qemu.sh +++ b/lib/qemu.sh @@ -2,6 +2,7 @@ . ./lib/numbers.sh . ./lib/colors.sh +. ./lib/db.sh function create_tap { local tap_id="${1}" @@ -24,6 +25,7 @@ function qemu_start_vm { local mac="$(find_mac "${vpc_name}_br-${subnet_id}" "${ip}")" print_in_color "${COLOR_GREEN}" "Create tap tap${tap_id}" + add_in_db "vm" "${vm_name}" "${subnet_name}" "${tap_id}" create_tap "${tap_id}" "br-${subnet_id}" "${vpc_name}" print_in_color "${COLOR_GREEN}" "Start vm ${vm_name}" @@ -34,9 +36,35 @@ function qemu_start_vm { -smp 1 \ -serial "unix:/tmp/${vm_name}.sock,server,nowait" \ -monitor "unix:/tmp/${vm_name}.mon-sock,server,nowait" \ + -qmp "unix:/tmp/${vm_name}.qmp-sock,server,nowait" \ -display "none" \ -drive "file=${volume_path},if=virtio" \ -netdev "tap,id=net0,ifname=tap${tap_id},script=no,downscript=no" \ -device "virtio-net-pci,netdev=net0,mac=${mac}" \ -daemonize +} + +function qemu_stop_vm { + local vm_name="${1}" + local vm_def=$(get_from_db "vm" "${vm_name}") + local subnet_name="$(echo "${vm_def}" | cut -d\; -f 2)" + local tap_id="$(echo "${vm_def}" | cut -d\; -f 3)" + local subnet_def=$(get_from_db "subnet" "${subnet_name}") + local vpc_name="$(echo "${subnet_def}" | cut -d\; -f 2)" + + + local unix_path="/tmp/${vm_name}.qmp-sock" + + print_in_color "${COLOR_RED}" "Stop ${vm_name}" + echo '{ "execute": "qmp_capabilities" }' | socat - UNIX-CONNECT:"${unix_path}" + echo '{ "execute": "system_powerdown" }' | socat - UNIX-CONNECT:"${unix_path}" + + + print_in_color "${COLOR_RED}" "Delete tap${tap_id}" + ip -n "${vpc_name}" link del dev "tap${tap_id}" + delete_in_db "vm" "${vm_name}" + + print_in_color "${COLOR_GREY}" "Try to delete ${subnet_name}" + count_in_db "vm" "${subnet_name}" + [ "$?" -eq "0" ] && delete_subnet "${subnet_name}" } \ No newline at end of file