qvm-run 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. #!/usr/bin/python2
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. #
  23. from qubes.qubes import QubesVmCollection
  24. from qubes.qubes import QubesException
  25. from qubes.guihelpers import notify_error_qubes_manager
  26. from optparse import OptionParser
  27. import subprocess
  28. import socket
  29. import errno
  30. import dbus
  31. import time
  32. import sys
  33. import os
  34. import os.path
  35. notify_object = None
  36. # how long (in sec) to wait for VMs to shutdown
  37. # before killing them (when used with --wait option)
  38. from qubes.qubes import defaults
  39. def tray_notify(str, label, timeout = 3000):
  40. notify_object.Notify("Qubes", 0, label.icon, "Qubes", str, [], [], timeout, dbus_interface="org.freedesktop.Notifications")
  41. def tray_notify_error(str, timeout = 3000):
  42. notify_object.Notify("Qubes", 0, "dialog-error", "Qubes", str, [], [], timeout, dbus_interface="org.freedesktop.Notifications")
  43. def vm_run_cmd(vm, cmd, options):
  44. if options.shutdown:
  45. if options.verbose:
  46. print >> sys.stderr, "Shutting down VM: '{0}'...".format(vm.name)
  47. try:
  48. vm.shutdown(force=options.force)
  49. except (QubesException) as err:
  50. # "There are other VMs connected to this VM:"
  51. print >> sys.stderr, "ERROR: {0}".format(err)
  52. if str(err).startswith("There are other VMs connected"):
  53. print >> sys.stderr, "Shutdown them first or use --force switch"
  54. exit(1)
  55. return
  56. if options.pause:
  57. if options.verbose:
  58. print >> sys.stderr, "Pausing VM: '{0}'...".format(vm.name)
  59. vm.pause()
  60. return
  61. if options.unpause:
  62. if options.verbose:
  63. print >> sys.stderr, "UnPausing VM: '{0}'...".format(vm.name)
  64. vm.unpause()
  65. return
  66. if options.verbose:
  67. print >> sys.stderr, "Running command on VM: '{0}'...".format(vm.name)
  68. try:
  69. def tray_notify_generic(level, str):
  70. if level == "info":
  71. tray_notify(str, label=vm.label)
  72. elif level == "error":
  73. tray_notify_error(str)
  74. return vm.run(cmd, autostart = options.auto,
  75. verbose = options.verbose,
  76. user = options.user,
  77. notify_function = tray_notify_generic if options.tray else None,
  78. passio = options.passio, localcmd = options.localcmd, gui = options.gui)
  79. except QubesException as err:
  80. if options.tray:
  81. tray_notify_error(str(err))
  82. notify_error_qubes_manager(vm.name, str(err))
  83. print >> sys.stderr, "ERROR(%s): %s" % (str(vm.name), str(err))
  84. return 1
  85. def main():
  86. usage = "usage: %prog [options] [<vm-name>] [<cmd>]"
  87. parser = OptionParser (usage)
  88. parser.add_option ("-q", "--quiet", action="store_false", dest="verbose", default=True)
  89. parser.add_option ("-a", "--auto", action="store_true", dest="auto", default=False,
  90. help="Auto start the VM if not running")
  91. parser.add_option ("-u", "--user", action="store", dest="user", default=None,
  92. help="Run command in a VM as a specified user")
  93. parser.add_option ("--tray", action="store_true", dest="tray", default=False,
  94. help="Use tray notifications instead of stdout" )
  95. parser.add_option ("--all", action="store_true", dest="run_on_all_running", default=False,
  96. help="Run command on all currently running VMs (or all paused, in case of --unpause)")
  97. parser.add_option ("--exclude", action="append", dest="exclude_list",
  98. help="When --all is used: exclude this VM name (might be repeated)")
  99. parser.add_option ("--wait", action="store_true", dest="wait_for_shutdown", default=False,
  100. help="Wait for the VM(s) to shutdown")
  101. parser.add_option ("--shutdown", action="store_true", dest="shutdown", default=False,
  102. help="(deprecated) Do 'xl shutdown' for the VM(s) (can be combined this with --all and --wait)")
  103. parser.add_option ("--pause", action="store_true", dest="pause", default=False,
  104. help="Do 'xl pause' for the VM(s) (can be combined this with --all and --wait)")
  105. parser.add_option ("--unpause", action="store_true", dest="unpause", default=False,
  106. help="Do 'xl unpause' for the VM(s) (can be combined this with --all and --wait)")
  107. parser.add_option ("-p", "--pass-io", action="store_true", dest="passio", default=False,
  108. help="Pass stdin/stdout/stderr from remote program")
  109. parser.add_option ("--localcmd", action="store", dest="localcmd", default=None,
  110. help="With --pass-io, pass stdin/stdout/stderr to the given program")
  111. parser.add_option ("--force", action="store_true", dest="force", default=False,
  112. help="Force operation, even if may damage other VMs (eg shutdown of NetVM)")
  113. parser.add_option ("--nogui", action="store_false", dest="gui", default=True,
  114. help="Run command without gui")
  115. (options, args) = parser.parse_args ()
  116. if options.passio:
  117. options.verbose = False
  118. if options.shutdown:
  119. print >>sys.stderr, "WARNING: --shutdown is deprecated. Use qvm-shutdown instead."
  120. if (options.shutdown or options.pause or options.unpause):
  121. takes_cmd_argument = False
  122. else:
  123. takes_cmd_argument = True
  124. if options.run_on_all_running:
  125. if len(args) < 1 and takes_cmd_argument:
  126. parser.error ("You must provide a command to execute on all the VMs.")
  127. if len(args) > 1 or ((not takes_cmd_argument) and len(args) > 0):
  128. parser.error ("To many arguments...")
  129. cmdstr = args[0] if takes_cmd_argument else None
  130. else:
  131. if len (args) < 1 and not takes_cmd_argument:
  132. parser.error ("You must specify the VM name to shutdown/pause/unpause.")
  133. if len (args) < 2 and takes_cmd_argument:
  134. parser.error ("You must specify the VM name and the command to execute in the VM.")
  135. if len (args) > 2 or ((not takes_cmd_argument) and len(args) > 1):
  136. parser.error ("To many arguments...")
  137. vmname = args[0]
  138. cmdstr = args[1] if takes_cmd_argument else None
  139. if options.tray:
  140. global notify_object
  141. notify_object = dbus.SessionBus().get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
  142. qvm_collection = QubesVmCollection()
  143. qvm_collection.lock_db_for_reading()
  144. qvm_collection.load()
  145. qvm_collection.unlock_db()
  146. vms_list = []
  147. if options.run_on_all_running:
  148. all_vms = [vm for vm in qvm_collection.values()]
  149. for vm in all_vms:
  150. if options.exclude_list is not None and vm.name in options.exclude_list:
  151. continue
  152. if vm.qid == 0:
  153. continue
  154. if (options.unpause and vm.is_paused()) or (not options.unpause and vm.is_running()):
  155. vms_list.append (vm)
  156. # disable options incompatible with --all
  157. options.passio = False
  158. else:
  159. vm = qvm_collection.get_vm_by_name(vmname)
  160. if vm is None:
  161. print >> sys.stderr, "A VM with the name '{0}' does not exist in the system!".format(vmname)
  162. exit(1)
  163. vms_list.append(vm)
  164. for vm in vms_list:
  165. vm_run_cmd(vm, cmdstr, options)
  166. if options.wait_for_shutdown:
  167. if options.verbose:
  168. print >> sys.stderr, "Waiting for the VM(s) to shutdown..."
  169. shutdown_counter = 0
  170. while len (vms_list):
  171. if options.verbose:
  172. print >> sys.stderr, "Waiting for VMs: ", [vm.name for vm in vms_list]
  173. for vm in vms_list:
  174. if not vm.is_running():
  175. vms_list.remove (vm)
  176. if shutdown_counter > defaults["shutdown_counter_max"]:
  177. # kill the VM
  178. if options.verbose:
  179. print >> sys.stderr, "Killing the (apparently hanging) VM '{0}'...".format(vm.name)
  180. vm.force_shutdown()
  181. #vms_list.remove(vm)
  182. shutdown_counter += 1
  183. time.sleep (1)
  184. exit (0) # there is no point in executing the other daemons in the case of --wait
  185. main()