Skip to content

Instantly share code, notes, and snippets.

@qerub
Last active January 18, 2020 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qerub/5521952 to your computer and use it in GitHub Desktop.
Save qerub/5521952 to your computer and use it in GitHub Desktop.
Script to shutdown a libvirt VM/domain and wait for completion
#!/usr/bin/env ruby
require "libvirt"
def vm_sync_shutdown(name)
conn = Libvirt::open("qemu:///system")
dom = conn.lookup_domain_by_name(name)
# TODO: Use dom.state instead of dom.info.state when it gets available
fail("Domain is not running") unless dom.info.state == Libvirt::Domain::RUNNING
dom.shutdown
puts "Shut down domain..."
print "Waiting: "
STDOUT.flush
# TODO: Get rid of exception handler when above TODO is fixed
begin
until dom.info.state == Libvirt::Domain::SHUTOFF
print "."
STDOUT.flush
sleep 1
end
rescue Libvirt::RetrieveError
raise unless dom.info.state == Libvirt::Domain::SHUTOFF
end
puts
conn.close
end
if __FILE__ == $0
fail("Usage: <domain name>") unless ARGV.length == 1
vm_sync_shutdown(ARGV[0])
end
@feltcat
Copy link

feltcat commented Jan 17, 2020

Thanks for the useful script!

I think it would be best to print a newline just before the script exits.

@qerub
Copy link
Author

qerub commented Jan 18, 2020

@feltcat: Hey! Glad you liked it. It's funny how something like this can bubble up 5+ years after publishing. To your suggestion: what do you think about putting a simple puts just before conn.close?

@feltcat
Copy link

feltcat commented Jan 18, 2020

@feltcat: Hey! Glad you liked it. It's funny how something like this can bubble up 5+ years after publishing. To your suggestion: what do you think about putting a simple puts just before conn.close?

Yep, that should work well!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment