qvm-run 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. if notify_object:
  41. notify_object.Notify("Qubes", 0, label.icon, "Qubes", str, [], [], timeout, dbus_interface="org.freedesktop.Notifications")
  42. def tray_notify_error(str, timeout = 3000):
  43. if notify_object:
  44. notify_object.Notify("Qubes", 0, "dialog-error", "Qubes", str, [], [], timeout, dbus_interface="org.freedesktop.Notifications")
  45. def vm_run_cmd(vm, cmd, options):
  46. if options.shutdown:
  47. if options.verbose:
  48. print >> sys.stderr, "Shutting down VM: '{0}'...".format(vm.name)
  49. try:
  50. vm.shutdown(force=options.force)
  51. except (QubesException) as err:
  52. # "There are other VMs connected to this VM:"
  53. print >> sys.stderr, "ERROR: {0}".format(err)
  54. if str(err).startswith("There are other VMs connected"):
  55. print >> sys.stderr, "Shutdown them first or use --force switch"
  56. exit(1)
  57. return 0
  58. if options.pause:
  59. if options.verbose:
  60. print >> sys.stderr, "Pausing VM: '{0}'...".format(vm.name)
  61. vm.pause()
  62. return 0
  63. if options.unpause:
  64. if options.verbose:
  65. print >> sys.stderr, "UnPausing VM: '{0}'...".format(vm.name)
  66. vm.unpause()
  67. return 0
  68. if options.verbose:
  69. print >> sys.stderr, "Running command on VM: '{0}'...".format(vm.name)
  70. if options.passio and options.color_output:
  71. print "\033[0;31m",
  72. try:
  73. def tray_notify_generic(level, str):
  74. if level == "info":
  75. tray_notify(str, label=vm.label)
  76. elif level == "error":
  77. tray_notify_error(str)
  78. return vm.run(cmd, autostart = options.auto,
  79. verbose = options.verbose,
  80. user = options.user,
  81. notify_function = tray_notify_generic if options.tray else None,
  82. wait = options.passio, localcmd = options.localcmd,
  83. gui = options.gui, filter_esc = options.filter_esc)
  84. except QubesException as err:
  85. if options.passio and options.color_output:
  86. print "\033[0m",
  87. if options.tray:
  88. tray_notify_error(str(err))
  89. notify_error_qubes_manager(vm.name, str(err))
  90. print >> sys.stderr, "ERROR(%s): %s" % (str(vm.name), str(err))
  91. return 1
  92. finally:
  93. if options.passio and options.color_output:
  94. print "\033[0m",
  95. def main():
  96. usage = "usage: %prog [options] [<vm-name>] [<cmd>]"
  97. parser = OptionParser (usage)
  98. parser.add_option ("-q", "--quiet", action="store_false", dest="verbose", default=True)
  99. parser.add_option ("-a", "--auto", action="store_true", dest="auto", default=False,
  100. help="Auto start the VM if not running")
  101. parser.add_option ("-u", "--user", action="store", dest="user", default=None,
  102. help="Run command in a VM as a specified user")
  103. parser.add_option ("--tray", action="store_true", dest="tray", default=False,
  104. help="Use tray notifications instead of stdout" )
  105. parser.add_option ("--all", action="store_true", dest="run_on_all_running", default=False,
  106. help="Run command on all currently running VMs (or all paused, in case of --unpause)")
  107. parser.add_option ("--exclude", action="append", dest="exclude_list",
  108. help="When --all is used: exclude this VM name (may be "
  109. "repeated)")
  110. parser.add_option ("--wait", action="store_true", dest="wait_for_shutdown", default=False,
  111. help="Wait for the VM(s) to shutdown")
  112. parser.add_option ("--shutdown", action="store_true", dest="shutdown", default=False,
  113. help="(deprecated) Do 'xl shutdown' for the VM(s) (can be combined this with --all and --wait)")
  114. parser.add_option ("--pause", action="store_true", dest="pause", default=False,
  115. help="Do 'xl pause' for the VM(s) (can be combined this with --all and --wait)")
  116. parser.add_option ("--unpause", action="store_true", dest="unpause", default=False,
  117. help="Do 'xl unpause' for the VM(s) (can be combined this with --all and --wait)")
  118. parser.add_option ("-p", "--pass-io", action="store_true", dest="passio", default=False,
  119. help="Pass stdin/stdout/stderr from remote program (implies -q)")
  120. parser.add_option ("--localcmd", action="store", dest="localcmd", default=None,
  121. help="With --pass-io, pass stdin/stdout/stderr to the given program")
  122. parser.add_option ("--force", action="store_true", dest="force", default=False,
  123. help="Force operation, even if may damage other VMs (eg shutdown of NetVM)")
  124. parser.add_option ("--nogui", action="store_false", dest="gui", default=True,
  125. help="Run command without gui")
  126. parser.add_option ("--filter-escape-chars", action="store_true",
  127. dest="filter_esc",
  128. default=os.isatty(sys.stdout.fileno()),
  129. help="Filter terminal escape sequences (default if "
  130. "output is terminal)")
  131. parser.add_option("--no-filter-escape-chars", action="store_false",
  132. dest="filter_esc",
  133. help="Do not filter terminal escape sequences - "
  134. "overrides --filter-escape-chars, DANGEROUS when "
  135. "output is terminal")
  136. parser.add_option("--no-color-output", action="store_false",
  137. dest="color_output", default=None,
  138. help="Disable marking VM output with red color")
  139. (options, args) = parser.parse_args ()
  140. if options.passio and options.run_on_all_running:
  141. parser.error ("Options --all and --pass-io cannot be used together")
  142. if options.passio:
  143. options.verbose = False
  144. if options.color_output is None:
  145. options.color_output = os.isatty(sys.stdout.fileno())
  146. if options.shutdown:
  147. print >>sys.stderr, "WARNING: --shutdown is deprecated. Use qvm-shutdown instead."
  148. if (options.shutdown or options.pause or options.unpause):
  149. takes_cmd_argument = False
  150. else:
  151. takes_cmd_argument = True
  152. if options.run_on_all_running:
  153. if len(args) < 1 and takes_cmd_argument:
  154. parser.error ("You must provide a command to execute on all the VMs.")
  155. if len(args) > 1 or ((not takes_cmd_argument) and len(args) > 0):
  156. parser.error ("To many arguments...")
  157. cmdstr = args[0] if takes_cmd_argument else None
  158. else:
  159. if len (args) < 1 and not takes_cmd_argument:
  160. parser.error ("You must specify the VM name to shutdown/pause/unpause.")
  161. if len (args) < 2 and takes_cmd_argument:
  162. parser.error ("You must specify the VM name and the command to execute in the VM.")
  163. if len (args) > 2 or ((not takes_cmd_argument) and len(args) > 1):
  164. parser.error ("To many arguments...")
  165. vmname = args[0]
  166. cmdstr = args[1] if takes_cmd_argument else None
  167. if options.tray:
  168. global notify_object
  169. try:
  170. notify_object = dbus.SessionBus().get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
  171. except dbus.DBusException as ex:
  172. print >>sys.stderr, "WARNING: failed connect to tray notification service: %s" % str(ex)
  173. qvm_collection = QubesVmCollection()
  174. qvm_collection.lock_db_for_reading()
  175. qvm_collection.load()
  176. qvm_collection.unlock_db()
  177. vms_list = []
  178. if options.run_on_all_running:
  179. all_vms = [vm for vm in qvm_collection.values()]
  180. for vm in all_vms:
  181. if options.exclude_list is not None and vm.name in options.exclude_list:
  182. continue
  183. if vm.qid == 0:
  184. continue
  185. if (options.unpause and vm.is_paused()) or (not options.unpause and vm.is_running()):
  186. vms_list.append (vm)
  187. # disable options incompatible with --all
  188. options.passio = False
  189. else:
  190. vm = qvm_collection.get_vm_by_name(vmname)
  191. if vm is None:
  192. print >> sys.stderr, "A VM with the name '{0}' does not exist in the system!".format(vmname)
  193. exit(1)
  194. vms_list.append(vm)
  195. retcode = 0
  196. for vm in vms_list:
  197. r = vm_run_cmd(vm, cmdstr, options)
  198. retcode = max(r, retcode)
  199. if options.wait_for_shutdown:
  200. if options.verbose:
  201. print >> sys.stderr, "Waiting for the VM(s) to shutdown..."
  202. shutdown_counter = 0
  203. while len (vms_list):
  204. if options.verbose:
  205. print >> sys.stderr, "Waiting for VMs: ", [vm.name for vm in vms_list]
  206. for vm in vms_list:
  207. if not vm.is_running():
  208. vms_list.remove (vm)
  209. if shutdown_counter > defaults["shutdown_counter_max"]:
  210. # kill the VM
  211. if options.verbose:
  212. print >> sys.stderr, "Killing the (apparently hanging) VM '{0}'...".format(vm.name)
  213. vm.force_shutdown()
  214. #vms_list.remove(vm)
  215. shutdown_counter += 1
  216. time.sleep (1)
  217. exit (0) # there is no point in executing the other daemons in the case of --wait
  218. exit(retcode)
  219. main()