qvm-run 10 KB

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