qvm-run 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. #!/usr/bin/python2.6
  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 optparse import OptionParser
  26. import subprocess
  27. import socket
  28. import errno
  29. import dbus
  30. import time
  31. qubes_guid_path = "/usr/bin/qubes_guid"
  32. qubes_clipd_path = "/usr/bin/qclipd"
  33. qubes_qfilexchgd_path= "/usr/bin/qfilexchgd"
  34. notify_object = None
  35. # how long (in sec) to wait for VMs to shutdown
  36. # before killing them (when used with --wait option)
  37. shutdown_counter_max = 30
  38. def tray_notify(str, label, timeout = 3000):
  39. notify_object.Notify("Qubes", 0, label.icon, "Qubes", str, [], [], timeout, dbus_interface="org.freedesktop.Notifications")
  40. def tray_notify_error(str, timeout = 3000):
  41. notify_object.Notify("Qubes", 0, "dialog-error", "Qubes", str, [], [], timeout, dbus_interface="org.freedesktop.Notifications")
  42. def vm_run_cmd(vm, cmd, options):
  43. if options.shutdown:
  44. if options.verbose:
  45. print "Shutting down VM: '{0}'...".format(vm.name)
  46. subprocess.call (["/usr/sbin/xm", "shutdown", vm.name])
  47. return
  48. if options.pause:
  49. if options.verbose:
  50. print "Pausing VM: '{0}'...".format(vm.name)
  51. subprocess.call (["/usr/sbin/xm", "pause", vm.name])
  52. return
  53. if options.unpause:
  54. if options.verbose:
  55. print "UnPausing VM: '{0}'...".format(vm.name)
  56. subprocess.call (["/usr/sbin/xm", "unpause", vm.name])
  57. return
  58. if options.verbose:
  59. print "Running command on VM: '{0}'...".format(vm.name)
  60. if not vm.is_running():
  61. if not options.auto:
  62. print "VM '{0}' is not running, please start it first, or use the '--auto' switch"
  63. exit (1)
  64. try:
  65. if options.verbose:
  66. print "Starting the VM '{0}'...".format(vm.name)
  67. if options.tray:
  68. tray_notify ("Starting the '{0}' VM...".format(vm.name), label=vm.label)
  69. xid = vm.start(verbose=options.verbose)
  70. except (IOError, OSError, QubesException) as err:
  71. print "ERROR: {0}".format(err)
  72. if options.tray:
  73. tray_notify_error ("Error while starting the '{0}' VM: {1}".format(vm.name, err))
  74. exit (1)
  75. except (MemoryError) as err:
  76. print "ERROR: {0}".format(err)
  77. print "Close one or more running VMs and try again."
  78. if options.tray:
  79. subprocess.call(["kdialog", "--error", "Not enough memory to start '{0}' VM! Close one or more running VMs and try again.".format(vm.name)])
  80. exit (1)
  81. if options.verbose:
  82. print "--> Starting Qubes GUId..."
  83. retcode = subprocess.call ([qubes_guid_path, "-d", str(xid), "-c", vm.label.color, "-e", cmd, "-i", vm.label.icon, "-l", str(vm.label.index)])
  84. if (retcode != 0) :
  85. print "ERROR: Cannot start qubes_guid!"
  86. if options.tray:
  87. tray_notify_error ("ERROR: Cannot start qubes_guid!")
  88. exit (1)
  89. else: # VM already running...
  90. guid_is_running = True
  91. xid = vm.get_xid()
  92. s = socket.socket (socket.AF_UNIX)
  93. try:
  94. s.connect ("/var/run/qubes/cmd_socket.{0}".format(xid))
  95. except (IOError, OSError) as e:
  96. if e.errno in [errno.ENOENT,errno.ECONNREFUSED]:
  97. guid_is_running = False
  98. else:
  99. print "ERROR: unix-connect: {0}".format(e)
  100. if options.tray:
  101. tray_notify_error ("ERROR: Cannot connect to GUI daemon for this VM!")
  102. exit(1)
  103. if guid_is_running:
  104. s.send (cmd)
  105. s.close()
  106. else:
  107. retcode = subprocess.call ([qubes_guid_path, "-d", str(xid), "-c", vm.label.color, "-e", cmd, "-i", vm.label.icon, "-l", str(vm.label.index)])
  108. if (retcode != 0) :
  109. print "ERROR: Cannot start qubes_guid!"
  110. if options.tray:
  111. tray_notify_error ("ERROR: Cannot start the GUI daemon for this VM!")
  112. exit (1)
  113. def main():
  114. usage = "usage: %prog [options] [<vm-name>] [<cmd>]"
  115. parser = OptionParser (usage)
  116. parser.add_option ("-q", "--quiet", action="store_false", dest="verbose", default=True)
  117. parser.add_option ("-a", "--auto", action="store_true", dest="auto", default=False,
  118. help="Auto start the VM if not running")
  119. parser.add_option ("-u", "--user", action="store", dest="user", default="user",
  120. help="Run command in a VM as a specified user")
  121. parser.add_option ("--tray", action="store_true", dest="tray", default=False,
  122. help="Use tray notifications instead of stdout" )
  123. parser.add_option ("--all", action="store_true", dest="run_on_all_running", default=False,
  124. help="Run command on all currently running VMs (or all paused, in case of --unpause)")
  125. parser.add_option ("--exclude", action="append", dest="exclude_list",
  126. help="When --all is used: exclude this VM name (might be repeated)")
  127. parser.add_option ("--wait", action="store_true", dest="wait_for_shutdown", default=False,
  128. help="Wait for the VM(s) to shutdown")
  129. parser.add_option ("--shutdown", action="store_true", dest="shutdown", default=False,
  130. help="Do 'xm shutdown' for the VM(s) (can be combined this with --all and --wait)")
  131. parser.add_option ("--pause", action="store_true", dest="pause", default=False,
  132. help="Do 'xm pause' for the VM(s) (can be combined this with --all and --wait)")
  133. parser.add_option ("--unpause", action="store_true", dest="unpause", default=False,
  134. help="Do 'xm unpause' for the VM(s) (can be combined this with --all and --wait)")
  135. (options, args) = parser.parse_args ()
  136. if (options.shutdown or options.pause or options.unpause):
  137. takes_cmd_argument = False
  138. else:
  139. takes_cmd_argument = True
  140. if options.run_on_all_running:
  141. if len(args) < 1 and takes_cmd_argument:
  142. parser.error ("You must provide a command to execute on all the VMs.")
  143. if len(args) > 1 or ((not takes_cmd_argument) and len(args) > 0):
  144. parser.error ("To many arguments...")
  145. cmdstr = args[0] if takes_cmd_argument else None
  146. else:
  147. if len (args) < 1 and not takes_cmd_argument:
  148. parser.error ("You must specify the VM name to shutdown/pause/unpause.")
  149. if len (args) < 2 and takes_cmd_argument:
  150. parser.error ("You must specify the VM name and the command to execute in the VM.")
  151. if len (args) > 2 or ((not takes_cmd_argument) and len(args) > 1):
  152. parser.error ("To many arguments...")
  153. vmname = args[0]
  154. cmdstr = args[1] if takes_cmd_argument else None
  155. if options.tray:
  156. global notify_object
  157. notify_object = dbus.SessionBus().get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
  158. qvm_collection = QubesVmCollection()
  159. qvm_collection.lock_db_for_reading()
  160. qvm_collection.load()
  161. qvm_collection.unlock_db()
  162. vms_list = []
  163. if options.run_on_all_running:
  164. all_vms = [vm for vm in qvm_collection.values()]
  165. for vm in all_vms:
  166. if options.exclude_list is not None and vm.name in options.exclude_list:
  167. continue
  168. if vm.qid == 0:
  169. continue
  170. if (options.unpause and vm.is_paused()) or (not options.unpause and vm.is_running()):
  171. vms_list.append (vm)
  172. else:
  173. vm = qvm_collection.get_vm_by_name(vmname)
  174. if vm is None:
  175. print "A VM with the name '{0}' does not exist in the system!".format(vmname)
  176. exit(1)
  177. vms_list.append(vm)
  178. if takes_cmd_argument:
  179. cmd = "{user}:{cmd}".format(user=options.user, cmd=cmdstr)
  180. else:
  181. cmd = None
  182. for vm in vms_list:
  183. vm_run_cmd(vm, cmd, options)
  184. if options.wait_for_shutdown:
  185. if options.verbose:
  186. print "Waiting for the VM(s) to shutdown..."
  187. shutdown_counter = 0
  188. while len (vms_list):
  189. if options.verbose:
  190. print "Waiting for VMs: ", [vm.name for vm in vms_list]
  191. for vm in vms_list:
  192. if not vm.is_running():
  193. vms_list.remove (vm)
  194. if shutdown_counter > shutdown_counter_max:
  195. # kill the VM
  196. if options.verbose:
  197. print "Killing the (apparently hanging) VM '{0}'...".format(vm.name)
  198. vm.force_shutdown()
  199. #vms_list.remove(vm)
  200. shutdown_counter += 1
  201. time.sleep (1)
  202. exit (0) # there is no point in executing the other daemons in the case of --wait
  203. retcode = subprocess.call([qubes_clipd_path])
  204. if retcode != 0:
  205. print "ERROR: Cannot start qclipd!"
  206. if options.tray:
  207. tray_notify ("ERROR: Cannot start the Qubes Clipboard Notifier!")
  208. retcode = subprocess.call([qubes_qfilexchgd_path])
  209. if retcode != 0:
  210. print "ERROR: Cannot start qfilexchgd!"
  211. if options.tray:
  212. tray_notify ("ERROR: Cannot start the Qubes Inter-VM File Exchange Daemon!")
  213. main()