main.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137
  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. #
  7. # This program is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU General Public License
  9. # as published by the Free Software Foundation; either version 2
  10. # of the License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  20. #
  21. #
  22. import sys
  23. import os
  24. import os.path
  25. import signal
  26. import subprocess
  27. import time
  28. from datetime import datetime, timedelta
  29. from PyQt4.QtGui import *
  30. from PyQt4.QtDBus import QDBusVariant, QDBusMessage
  31. from PyQt4.QtDBus import QDBusConnection
  32. from PyQt4.QtDBus import QDBusInterface, QDBusAbstractAdaptor
  33. from pyinotify import WatchManager, ThreadedNotifier, EventsCodes, \
  34. ProcessEvent
  35. from qubes.qubes import QubesVmCollection
  36. from qubes.qubes import QubesException
  37. from qubes.qubes import system_path
  38. from qubes.qubes import QubesDaemonPidfile
  39. from qubes.qubes import QubesHost
  40. from qubesmanager.about import AboutDialog
  41. import table_widgets
  42. from block import QubesBlockDevicesManager
  43. from table_widgets import VmTypeWidget, VmLabelWidget, VmNameItem, \
  44. VmInfoWidget, VmTemplateItem, VmNetvmItem, VmUsageBarWidget, ChartWidget, \
  45. VmSizeOnDiskItem, VmInternalItem, VmIPItem, VmIncludeInBackupsItem, \
  46. VmLastBackupItem
  47. from qubes.qubes import QubesHVm
  48. from qubes import qubesutils
  49. from ui_mainwindow import *
  50. from create_new_vm import NewVmDlg
  51. from settings import VMSettingsWindow
  52. from restore import RestoreVMsWindow
  53. from backup import BackupVMsWindow
  54. from global_settings import GlobalSettingsWindow
  55. from log_dialog import LogDialog
  56. from thread_monitor import *
  57. qubes_clipboard_info_file = "/var/run/qubes/qubes-clipboard.bin.source"
  58. update_suggestion_interval = 14 # 14 days
  59. dbus_object_path = '/org/qubesos/QubesManager'
  60. dbus_interface = 'org.qubesos.QubesManager'
  61. system_bus = None
  62. session_bus = None
  63. class QMVmState:
  64. ErrorMsg = 1
  65. AudioRecAvailable = 2
  66. AudioRecAllowed = 3
  67. class QubesManagerFileWatcher(ProcessEvent):
  68. def __init__(self, update_func, **kargs):
  69. super(QubesManagerFileWatcher, self).__init__(**kargs)
  70. self.update_func = update_func
  71. def process_IN_MODIFY(self, event):
  72. if event.path == system_path["qubes_store_filename"]:
  73. self.update_func()
  74. def process_IN_MOVED_TO(self, event):
  75. if event.pathname == system_path["qubes_store_filename"]:
  76. self.update_func()
  77. # noinspection PyMethodMayBeStatic
  78. def process_IN_CLOSE_WRITE(self, event):
  79. if event.path == qubes_clipboard_info_file:
  80. src_info_file = open(qubes_clipboard_info_file, 'r')
  81. src_vmname = src_info_file.readline().strip('\n')
  82. if src_vmname == "":
  83. trayIcon.showMessage(
  84. "Qubes Clipboard has been copied to the VM and wiped.<i/>\n"
  85. "<small>Trigger a paste operation (e.g. Ctrl-v) to insert "
  86. "it into an application.</small>",
  87. msecs=3000)
  88. else:
  89. trayIcon.showMessage(
  90. "Qubes Clipboard fetched from VM: <b>'{0}'</b>\n"
  91. "<small>Press Ctrl-Shift-v to copy this clipboard into dest"
  92. " VM's clipboard.</small>".format(
  93. src_vmname), msecs=3000)
  94. src_info_file.close()
  95. def process_IN_CREATE(self, event):
  96. if event.name == os.path.basename(qubes_clipboard_info_file):
  97. event.path = qubes_clipboard_info_file
  98. self.process_IN_CLOSE_WRITE(event)
  99. wm.add_watch(qubes_clipboard_info_file,
  100. EventsCodes.OP_FLAGS.get('IN_CLOSE_WRITE'))
  101. elif event.name == os.path.basename(table_widgets
  102. .qubes_dom0_updates_stat_file):
  103. trayIcon.showMessage("Qubes dom0 updates available.", msecs=0)
  104. class VmRowInTable(object):
  105. cpu_graph_hue = 210
  106. mem_graph_hue = 120
  107. def __init__(self, vm, row_no, table, block_manager):
  108. self.vm = vm
  109. self.row_no = row_no
  110. table_widgets.row_height = VmManagerWindow.row_height
  111. table.setRowHeight(row_no, VmManagerWindow.row_height)
  112. self.type_widget = VmTypeWidget(vm)
  113. table.setCellWidget(row_no, VmManagerWindow.columns_indices['Type'],
  114. self.type_widget)
  115. table.setItem(row_no, VmManagerWindow.columns_indices['Type'],
  116. self.type_widget.tableItem)
  117. self.label_widget = VmLabelWidget(vm)
  118. table.setCellWidget(row_no, VmManagerWindow.columns_indices['Label'],
  119. self.label_widget)
  120. table.setItem(row_no, VmManagerWindow.columns_indices['Label'],
  121. self.label_widget.tableItem)
  122. self.name_widget = VmNameItem(vm)
  123. table.setItem(row_no, VmManagerWindow.columns_indices['Name'],
  124. self.name_widget)
  125. self.info_widget = VmInfoWidget(vm)
  126. table.setCellWidget(row_no, VmManagerWindow.columns_indices['State'],
  127. self.info_widget)
  128. table.setItem(row_no, VmManagerWindow.columns_indices['State'],
  129. self.info_widget.tableItem)
  130. self.template_widget = VmTemplateItem(vm)
  131. table.setItem(row_no, VmManagerWindow.columns_indices['Template'],
  132. self.template_widget)
  133. self.netvm_widget = VmNetvmItem(vm)
  134. table.setItem(row_no, VmManagerWindow.columns_indices['NetVM'],
  135. self.netvm_widget)
  136. self.cpu_usage_widget = VmUsageBarWidget(
  137. 0, 100, "%v %",
  138. lambda v, val: val if v.last_running else 0,
  139. vm, 0, self.cpu_graph_hue)
  140. table.setCellWidget(row_no, VmManagerWindow.columns_indices['CPU'],
  141. self.cpu_usage_widget)
  142. table.setItem(row_no, VmManagerWindow.columns_indices['CPU'],
  143. self.cpu_usage_widget.tableItem)
  144. self.load_widget = ChartWidget(
  145. vm,
  146. lambda v, val: val if v.last_running else 0,
  147. self.cpu_graph_hue, 0)
  148. table.setCellWidget(row_no,
  149. VmManagerWindow.columns_indices['CPU Graph'],
  150. self.load_widget)
  151. table.setItem(row_no, VmManagerWindow.columns_indices['CPU Graph'],
  152. self.load_widget.tableItem)
  153. self.mem_usage_widget = VmUsageBarWidget(
  154. 0, qubes_host.memory_total / 1024, "%v MB",
  155. lambda v, val: v.get_mem() / 1024,
  156. vm, 0, self.mem_graph_hue)
  157. table.setCellWidget(row_no, VmManagerWindow.columns_indices['MEM'],
  158. self.mem_usage_widget)
  159. table.setItem(row_no, VmManagerWindow.columns_indices['MEM'],
  160. self.mem_usage_widget.tableItem)
  161. self.mem_widget = ChartWidget(
  162. vm, lambda v, val: v.get_mem() * 100 / qubes_host.memory_total,
  163. self.mem_graph_hue, 0)
  164. table.setCellWidget(row_no,
  165. VmManagerWindow.columns_indices['MEM Graph'],
  166. self.mem_widget)
  167. table.setItem(row_no, VmManagerWindow.columns_indices['MEM Graph'],
  168. self.mem_widget.tableItem)
  169. self.size_widget = VmSizeOnDiskItem(vm)
  170. table.setItem(row_no, VmManagerWindow.columns_indices['Size'],
  171. self.size_widget)
  172. self.internal_widget = VmInternalItem(vm)
  173. table.setItem(row_no, VmManagerWindow.columns_indices['Internal'],
  174. self.internal_widget)
  175. self.ip_widget = VmIPItem(vm)
  176. table.setItem(row_no, VmManagerWindow.columns_indices['IP'],
  177. self.ip_widget)
  178. self.include_in_backups_widget = VmIncludeInBackupsItem(vm)
  179. table.setItem(row_no, VmManagerWindow.columns_indices[
  180. 'Backups'], self.include_in_backups_widget)
  181. self.last_backup_widget = VmLastBackupItem(vm)
  182. table.setItem(row_no, VmManagerWindow.columns_indices[
  183. 'Last backup'], self.last_backup_widget)
  184. def update(self, blk_visible=None, cpu_load=None, update_size_on_disk=False,
  185. rec_visible=None):
  186. """
  187. Update info in a single VM row
  188. :param blk_visible: if not None, show/hide block icon, otherwise
  189. don't change its visibility
  190. :param cpu_load: current CPU load (if applicable), in percents
  191. :param update_size_on_disk: should disk utilization be updated? the
  192. widget will extract the data from VM object
  193. :param rec_visible: if not None, show/hide mic icon, otherwise don't
  194. change its visibility
  195. :return: None
  196. """
  197. self.info_widget.update_vm_state(self.vm, blk_visible, rec_visible)
  198. if cpu_load is not None:
  199. self.cpu_usage_widget.update_load(self.vm, cpu_load)
  200. self.mem_usage_widget.update_load(self.vm, None)
  201. self.load_widget.update_load(self.vm, cpu_load)
  202. self.mem_widget.update_load(self.vm, None)
  203. if update_size_on_disk:
  204. self.size_widget.update()
  205. vm_shutdown_timeout = 20000 # in msec
  206. vm_restart_check_timeout= 1000 # in msec
  207. class VmShutdownMonitor(QObject):
  208. def __init__(self, vm, shutdown_time=vm_shutdown_timeout, check_time=vm_restart_check_timeout, and_restart=False, caller=None):
  209. QObject.__init__(self)
  210. self.vm = vm
  211. self.shutdown_time = shutdown_time
  212. self.check_time = check_time
  213. self.and_restart = and_restart
  214. self.shutdown_started = datetime.now()
  215. self.caller = caller
  216. def check_if_vm_has_shutdown(self):
  217. vm = self.vm
  218. vm_start_time = vm.get_start_time()
  219. if vm.is_running() and vm_start_time and \
  220. vm_start_time < self.shutdown_started:
  221. if (datetime.now() - self.shutdown_started) > \
  222. timedelta(milliseconds=self.shutdown_time):
  223. reply = QMessageBox.question(
  224. None, "VM Shutdown",
  225. "The VM <b>'{0}'</b> hasn't shutdown within the last "
  226. "{1} seconds, do you want to kill it?<br>".format(
  227. vm.name, self.shutdown_time / 1000),
  228. "Kill it!",
  229. "Wait another {0} seconds...".format(
  230. self.shutdown_time / 1000))
  231. if reply == 0:
  232. vm.force_shutdown()
  233. if self.and_restart:
  234. if self.caller:
  235. self.caller.start_vm(vm)
  236. else:
  237. # noinspection PyTypeChecker,PyCallByClass
  238. self.shutdown_started = datetime.now()
  239. QTimer.singleShot(self.check_time,
  240. self.check_if_vm_has_shutdown)
  241. else:
  242. QTimer.singleShot(self.check_time,
  243. self.check_if_vm_has_shutdown)
  244. else:
  245. if self.and_restart:
  246. if self.caller:
  247. self.caller.start_vm(vm)
  248. class VmManagerWindow(Ui_VmManagerWindow, QMainWindow):
  249. row_height = 30
  250. column_width = 200
  251. min_visible_rows = 10
  252. update_interval = 1000 # in msec
  253. show_inactive_vms = True
  254. show_internal_vms = False
  255. search = ""
  256. # suppress saving settings while initializing widgets
  257. settings_loaded = False
  258. columns_indices = {"Type": 0,
  259. "Label": 1,
  260. "Name": 2,
  261. "State": 3,
  262. "Template": 4,
  263. "NetVM": 5,
  264. "CPU": 6,
  265. "CPU Graph": 7,
  266. "MEM": 8,
  267. "MEM Graph": 9,
  268. "Size": 10,
  269. "Internal": 11,
  270. "IP": 12,
  271. "Backups": 13,
  272. "Last backup": 14,
  273. }
  274. def __init__(self, qvm_collection, blk_manager, parent=None):
  275. super(VmManagerWindow, self).__init__()
  276. self.setupUi(self)
  277. self.toolbar = self.toolBar
  278. self.manager_settings = QSettings()
  279. self.qubes_watch = qubesutils.QubesWatch()
  280. self.qvm_collection = qvm_collection
  281. self.blk_manager = blk_manager
  282. self.blk_manager.tray_message_func = trayIcon.showMessage
  283. self.qubes_watch.setup_domain_watch(self.domain_state_changed_callback)
  284. self.qubes_watch.setup_block_watch(self.blk_manager.block_devs_event)
  285. self.blk_watch_thread = threading.Thread(
  286. target=self.qubes_watch.watch_loop)
  287. self.blk_watch_thread.daemon = True
  288. self.blk_watch_thread.start()
  289. self.connect(self.table, SIGNAL("itemSelectionChanged()"),
  290. self.table_selection_changed)
  291. self.table.setColumnWidth(0, self.column_width)
  292. self.sort_by_column = "Type"
  293. self.sort_order = Qt.AscendingOrder
  294. self.screen_number = -1
  295. self.screen_changed = False
  296. self.vms_list = []
  297. self.vms_in_table = {}
  298. self.reload_table = False
  299. self.running_vms_count = 0
  300. self.internal_vms_count = 0
  301. self.vm_errors = {}
  302. self.vm_rec = {}
  303. self.frame_width = 0
  304. self.frame_height = 0
  305. self.move(self.x(), 0)
  306. self.columns_actions = {
  307. self.columns_indices["Type"]: self.action_vm_type,
  308. self.columns_indices["Label"]: self.action_label,
  309. self.columns_indices["Name"]: self.action_name,
  310. self.columns_indices["State"]: self.action_state,
  311. self.columns_indices["Template"]: self.action_template,
  312. self.columns_indices["NetVM"]: self.action_netvm,
  313. self.columns_indices["CPU"]: self.action_cpu,
  314. self.columns_indices["CPU Graph"]: self.action_cpu_graph,
  315. self.columns_indices["MEM"]: self.action_mem,
  316. self.columns_indices["MEM Graph"]: self.action_mem_graph,
  317. self.columns_indices["Size"]: self.action_size_on_disk,
  318. self.columns_indices["Internal"]: self.action_internal,
  319. self.columns_indices["IP"]: self
  320. .action_ip, self.columns_indices["Backups"]: self
  321. .action_backups, self.columns_indices["Last backup"]: self
  322. .action_last_backup
  323. }
  324. self.visible_columns_count = len(self.columns_indices)
  325. self.table.setColumnHidden(self.columns_indices["NetVM"], True)
  326. self.action_netvm.setChecked(False)
  327. self.table.setColumnHidden(self.columns_indices["CPU Graph"], True)
  328. self.action_cpu_graph.setChecked(False)
  329. self.table.setColumnHidden(self.columns_indices["MEM Graph"], True)
  330. self.action_mem_graph.setChecked(False)
  331. self.table.setColumnHidden(self.columns_indices["Size"], True)
  332. self.action_size_on_disk.setChecked(False)
  333. self.table.setColumnHidden(self.columns_indices["Internal"], True)
  334. self.action_internal.setChecked(False)
  335. self.table.setColumnHidden(self.columns_indices["IP"], True)
  336. self.action_ip.setChecked(False)
  337. self.table.setColumnHidden(self.columns_indices["Backups"], True)
  338. self.action_backups.setChecked(False)
  339. self.table.setColumnHidden(self.columns_indices["Last backup"], True)
  340. self.action_last_backup.setChecked(False)
  341. self.table.setColumnWidth(self.columns_indices["State"], 80)
  342. self.table.setColumnWidth(self.columns_indices["Name"], 150)
  343. self.table.setColumnWidth(self.columns_indices["Label"], 40)
  344. self.table.setColumnWidth(self.columns_indices["Type"], 40)
  345. self.table.setColumnWidth(self.columns_indices["Size"], 100)
  346. self.table.setColumnWidth(self.columns_indices["Internal"], 60)
  347. self.table.setColumnWidth(self.columns_indices["IP"], 100)
  348. self.table.setColumnWidth(self.columns_indices["Backups"], 60)
  349. self.table.setColumnWidth(self.columns_indices["Last backup"], 90)
  350. self.table.horizontalHeader().setResizeMode(QHeaderView.Fixed)
  351. self.table.sortItems(self.columns_indices[self.sort_by_column],
  352. self.sort_order)
  353. self.context_menu = QMenu(self)
  354. self.context_menu.addAction(self.action_settings)
  355. self.context_menu.addAction(self.action_editfwrules)
  356. self.context_menu.addAction(self.action_appmenus)
  357. self.context_menu.addAction(self.action_set_keyboard_layout)
  358. self.context_menu.addMenu(self.blk_menu)
  359. self.context_menu.addAction(self.action_toggle_audio_input)
  360. self.context_menu.addSeparator()
  361. self.context_menu.addAction(self.action_updatevm)
  362. self.context_menu.addAction(self.action_run_command_in_vm)
  363. self.context_menu.addAction(self.action_resumevm)
  364. self.context_menu.addAction(self.action_startvm_tools_install)
  365. self.context_menu.addAction(self.action_pausevm)
  366. self.context_menu.addAction(self.action_shutdownvm)
  367. self.context_menu.addAction(self.action_restartvm)
  368. self.context_menu.addAction(self.action_killvm)
  369. self.context_menu.addSeparator()
  370. self.context_menu.addAction(self.action_clonevm)
  371. self.context_menu.addAction(self.action_removevm)
  372. self.context_menu.addSeparator()
  373. self.context_menu.addMenu(self.logs_menu)
  374. self.context_menu.addSeparator()
  375. self.tools_context_menu = QMenu(self)
  376. self.tools_context_menu.addAction(self.action_toolbar)
  377. self.tools_context_menu.addAction(self.action_menubar)
  378. self.table_selection_changed()
  379. self.connect(
  380. self.table.horizontalHeader(),
  381. SIGNAL("sortIndicatorChanged(int, Qt::SortOrder)"),
  382. self.sortIndicatorChanged)
  383. self.connect(self.table,
  384. SIGNAL("customContextMenuRequested(const QPoint&)"),
  385. self.open_context_menu)
  386. self.connect(self.menubar,
  387. SIGNAL("customContextMenuRequested(const QPoint&)"),
  388. lambda pos: self.open_tools_context_menu(self.menubar,
  389. pos))
  390. self.connect(self.toolBar,
  391. SIGNAL("customContextMenuRequested(const QPoint&)"),
  392. lambda pos: self.open_tools_context_menu(self.toolBar,
  393. pos))
  394. self.connect(self.blk_menu, SIGNAL("triggered(QAction *)"),
  395. self.attach_dettach_device_triggered)
  396. self.connect(self.logs_menu, SIGNAL("triggered(QAction *)"),
  397. self.show_log)
  398. self.connect(self.searchbox, SIGNAL("textChanged(const QString&)"),
  399. self.do_search)
  400. self.table.setContentsMargins(0, 0, 0, 0)
  401. self.centralwidget.layout().setContentsMargins(0, 0, 0, 0)
  402. self.layout().setContentsMargins(0, 0, 0, 0)
  403. self.connect(self.action_menubar, SIGNAL("toggled(bool)"),
  404. self.showhide_menubar)
  405. self.connect(self.action_toolbar, SIGNAL("toggled(bool)"),
  406. self.showhide_toolbar)
  407. self.register_dbus_watches()
  408. self.load_manager_settings()
  409. self.action_showallvms.setChecked(self.show_inactive_vms)
  410. self.action_showinternalvms.setChecked(self.show_internal_vms)
  411. self.fill_table()
  412. self.counter = 0
  413. self.update_size_on_disk = False
  414. self.shutdown_monitor = {}
  415. self.last_measure_results = {}
  416. self.last_measure_time = time.time()
  417. # noinspection PyCallByClass,PyTypeChecker
  418. QTimer.singleShot(self.update_interval, self.update_table)
  419. QubesDbusNotifyServerAdaptor(self)
  420. def load_manager_settings(self):
  421. # visible columns
  422. self.manager_settings.beginGroup("columns")
  423. for col in self.columns_indices.keys():
  424. col_no = self.columns_indices[col]
  425. visible = self.manager_settings.value(
  426. col,
  427. defaultValue=not self.table.isColumnHidden(col_no)).toBool()
  428. self.columns_actions[col_no].setChecked(visible)
  429. self.manager_settings.endGroup()
  430. self.show_inactive_vms = self.manager_settings.value(
  431. "view/show_inactive_vms", defaultValue=False).toBool()
  432. self.show_internal_vms = self.manager_settings.value(
  433. "view/show_internal_vms", defaultValue=False).toBool()
  434. self.sort_by_column = str(
  435. self.manager_settings.value("view/sort_column",
  436. defaultValue=self.sort_by_column).toString())
  437. self.sort_order = Qt.SortOrder(
  438. self.manager_settings.value("view/sort_order",
  439. defaultValue=self.sort_order).toInt()[
  440. 0])
  441. self.table.sortItems(self.columns_indices[self.sort_by_column],
  442. self.sort_order)
  443. if not self.manager_settings.value("view/menubar_visible",
  444. defaultValue=True).toBool():
  445. self.action_menubar.setChecked(False)
  446. if not self.manager_settings.value("view/toolbar_visible",
  447. defaultValue=True).toBool():
  448. self.action_toolbar.setChecked(False)
  449. x = self.manager_settings.value('position/x', defaultValue=-1).toInt()[
  450. 0]
  451. y = self.manager_settings.value('position/y', defaultValue=-1).toInt()[
  452. 0]
  453. if x != -1 or y != -1:
  454. self.move(x, y)
  455. self.settings_loaded = True
  456. def show(self):
  457. super(VmManagerWindow, self).show()
  458. self.screen_number = app.desktop().screenNumber(self)
  459. def set_table_geom_size(self):
  460. desktop_width = app.desktop().availableGeometry(
  461. self).width() - self.frame_width # might be wrong...
  462. desktop_height = app.desktop().availableGeometry(
  463. self).height() - self.frame_height # might be wrong...
  464. desktop_height -= self.row_height # UGLY! to somehow ommit taskbar...
  465. w = self.table.horizontalHeader().length() + \
  466. self.table.verticalScrollBar().width() + \
  467. 2 * self.table.frameWidth() + 1
  468. h = self.table.horizontalHeader().height() + \
  469. 2 * self.table.frameWidth()
  470. mainwindow_to_add = 0
  471. available_space = desktop_height
  472. if self.menubar.isVisible():
  473. menubar_height = (self.menubar.sizeHint().height() +
  474. self.menubar.contentsMargins().top() +
  475. self.menubar.contentsMargins().bottom())
  476. available_space -= menubar_height
  477. mainwindow_to_add += menubar_height
  478. if self.toolbar.isVisible():
  479. toolbar_height = (self.toolbar.sizeHint().height() +
  480. self.toolbar.contentsMargins().top() +
  481. self.toolbar.contentsMargins().bottom())
  482. available_space -= toolbar_height
  483. mainwindow_to_add += toolbar_height
  484. if w >= desktop_width:
  485. available_space -= self.table.horizontalScrollBar().height()
  486. h += self.table.horizontalScrollBar().height()
  487. # account for search box height
  488. available_space -= self.searchbox.height()
  489. h += self.searchbox.height()
  490. default_rows = int(available_space / self.row_height)
  491. n = sum(not self.table.isRowHidden(row) for row in
  492. xrange(self.table.rowCount()))
  493. if n > default_rows:
  494. h += default_rows * self.row_height
  495. self.table.verticalScrollBar().show()
  496. else:
  497. h += n * self.row_height
  498. self.table.verticalScrollBar().hide()
  499. w -= self.table.verticalScrollBar().width()
  500. w = min(desktop_width, w)
  501. self.centralwidget.setFixedHeight(h)
  502. h += mainwindow_to_add
  503. self.setMaximumHeight(h)
  504. self.setMinimumHeight(h)
  505. self.table.setFixedWidth(w)
  506. self.centralwidget.setFixedWidth(w)
  507. # don't change the following two lines to setFixedWidth!
  508. self.setMaximumWidth(w)
  509. self.setMinimumWidth(w)
  510. def moveEvent(self, event):
  511. super(VmManagerWindow, self).moveEvent(event)
  512. screen_number = app.desktop().screenNumber(self)
  513. if self.screen_number != screen_number:
  514. self.screen_changed = True
  515. self.screen_number = screen_number
  516. if self.settings_loaded:
  517. self.manager_settings.setValue('position/x', self.x())
  518. self.manager_settings.setValue('position/y', self.y())
  519. # do not sync for performance reasons
  520. def domain_state_changed_callback(self, name=None, uuid=None):
  521. if name is not None:
  522. vm = self.qvm_collection.get_vm_by_name(name)
  523. if vm:
  524. vm.refresh()
  525. def get_vms_list(self):
  526. self.qvm_collection.lock_db_for_reading()
  527. self.qvm_collection.load()
  528. self.qvm_collection.unlock_db()
  529. running_count = 0
  530. internal_count = 0
  531. vms_list = [vm for vm in self.qvm_collection.values()]
  532. for vm in vms_list:
  533. vm.last_power_state = vm.get_power_state()
  534. vm.last_running = vm.is_running()
  535. if vm.last_running:
  536. running_count += 1
  537. if vm.internal:
  538. internal_count += 1
  539. vm.qubes_manager_state = {}
  540. self.update_audio_rec_info(vm)
  541. vm.qubes_manager_state[QMVmState.ErrorMsg] = self.vm_errors[
  542. vm.qid] if vm.qid in self.vm_errors else None
  543. self.running_vms_count = running_count
  544. self.internal_vms_count = internal_count
  545. return vms_list
  546. def fill_table(self):
  547. # save current selection
  548. row_index = self.table.currentRow()
  549. selected_qid = -1
  550. if row_index != -1:
  551. vm_item = self.table.item(row_index, self.columns_indices["Name"])
  552. if vm_item:
  553. selected_qid = vm_item.qid
  554. self.table.setSortingEnabled(False)
  555. self.table.clearContents()
  556. vms_list = self.get_vms_list()
  557. self.table.setRowCount(len(vms_list))
  558. vms_in_table = {}
  559. row_no = 0
  560. for vm in vms_list:
  561. # if vm.internal:
  562. # continue
  563. vm_row = VmRowInTable(vm, row_no, self.table, self.blk_manager)
  564. vms_in_table[vm.qid] = vm_row
  565. row_no += 1
  566. self.table.setRowCount(row_no)
  567. self.vms_list = vms_list
  568. self.vms_in_table = vms_in_table
  569. self.reload_table = False
  570. if selected_qid in vms_in_table.keys():
  571. self.table.setCurrentItem(
  572. self.vms_in_table[selected_qid].name_widget)
  573. self.table.setSortingEnabled(True)
  574. self.showhide_vms()
  575. self.set_table_geom_size()
  576. def showhide_vms(self):
  577. if self.show_inactive_vms and self.show_internal_vms and not self.search:
  578. for row_no in xrange(self.table.rowCount()):
  579. self.table.setRowHidden(row_no, False)
  580. else:
  581. for row_no in xrange(self.table.rowCount()):
  582. widget = self.table.cellWidget(row_no,
  583. self.columns_indices["State"])
  584. running = widget.vm.last_running
  585. internal = widget.vm.internal
  586. name = widget.vm.name
  587. show = (running or self.show_inactive_vms) and \
  588. (not internal or self.show_internal_vms) and \
  589. (self.search in widget.vm.name or not self.search)
  590. self.table.setRowHidden(row_no, not show)
  591. @pyqtSlot(str)
  592. def do_search(self, search):
  593. self.search = str(search)
  594. self.showhide_vms()
  595. self.set_table_geom_size()
  596. def mark_table_for_update(self):
  597. self.reload_table = True
  598. # When calling update_table() directly, always use out_of_schedule=True!
  599. def update_table(self, out_of_schedule=False):
  600. update_devs = self.update_block_devices() or out_of_schedule
  601. reload_table = self.reload_table
  602. if manager_window.isVisible():
  603. some_vms_have_changed_power_state = False
  604. for vm in self.vms_list:
  605. state = vm.get_power_state()
  606. if vm.last_power_state != state:
  607. if state == "Running" and \
  608. self.vm_errors.get(vm.qid, "") \
  609. .startswith("Error starting VM:"):
  610. self.clear_error(vm.qid)
  611. prev_running = vm.last_running
  612. vm.last_power_state = state
  613. vm.last_running = vm.is_running()
  614. self.update_audio_rec_info(vm)
  615. if not prev_running and vm.last_running:
  616. self.running_vms_count += 1
  617. some_vms_have_changed_power_state = True
  618. # Clear error state when VM just started
  619. self.clear_error(vm.qid)
  620. elif prev_running and not vm.last_running:
  621. # FIXME: remove when recAllowed state will be preserved
  622. if self.vm_rec.has_key(vm.name):
  623. self.vm_rec.pop(vm.name)
  624. self.running_vms_count -= 1
  625. some_vms_have_changed_power_state = True
  626. else:
  627. # pulseaudio agent register itself some time after VM
  628. # startup
  629. if state == "Running" and not vm.qubes_manager_state[
  630. QMVmState.AudioRecAvailable]:
  631. self.update_audio_rec_info(vm)
  632. if self.vm_errors.get(vm.qid, "") == \
  633. "Error starting VM: Cannot execute qrexec-daemon!" \
  634. and vm.is_qrexec_running():
  635. self.clear_error(vm.qid)
  636. if self.screen_changed:
  637. reload_table = True
  638. self.screen_changed = False
  639. if reload_table:
  640. self.fill_table()
  641. update_devs = True
  642. if not self.show_inactive_vms and \
  643. some_vms_have_changed_power_state:
  644. self.showhide_vms()
  645. self.set_table_geom_size()
  646. if self.sort_by_column == \
  647. "State" and some_vms_have_changed_power_state:
  648. self.table.sortItems(self.columns_indices[self.sort_by_column],
  649. self.sort_order)
  650. blk_visible = None
  651. rows_with_blk = None
  652. if update_devs:
  653. rows_with_blk = []
  654. self.blk_manager.blk_lock.acquire()
  655. for d in self.blk_manager.attached_devs:
  656. rows_with_blk.append(
  657. self.blk_manager.attached_devs[d]['attached_to'][
  658. 'vm'].qid)
  659. self.blk_manager.blk_lock.release()
  660. if (not self.table.isColumnHidden(self.columns_indices['Size'])) and \
  661. self.counter % 60 == 0 or out_of_schedule:
  662. self.update_size_on_disk = True
  663. if self.counter % 3 == 0 or out_of_schedule:
  664. (self.last_measure_time, self.last_measure_results) = \
  665. qubes_host.measure_cpu_usage(self.qvm_collection,
  666. self.last_measure_results,
  667. self.last_measure_time)
  668. for vm_row in self.vms_in_table.values():
  669. cur_cpu_load = None
  670. if vm_row.vm.get_xid() in self.last_measure_results:
  671. cur_cpu_load = self.last_measure_results[vm_row.vm.xid][
  672. 'cpu_usage']
  673. else:
  674. cur_cpu_load = 0
  675. if rows_with_blk is not None:
  676. if vm_row.vm.qid in rows_with_blk:
  677. blk_visible = True
  678. else:
  679. blk_visible = False
  680. vm_row.update(blk_visible=blk_visible,
  681. cpu_load=cur_cpu_load,
  682. update_size_on_disk=self.update_size_on_disk,
  683. rec_visible=self.vm_rec.get(vm_row.vm.name,
  684. False))
  685. else:
  686. for vm_row in self.vms_in_table.values():
  687. if rows_with_blk is not None:
  688. if vm_row.vm.qid in rows_with_blk:
  689. blk_visible = True
  690. else:
  691. blk_visible = False
  692. vm_row.update(blk_visible=blk_visible,
  693. update_size_on_disk=self.update_size_on_disk,
  694. rec_visible=self.vm_rec.get(vm_row.vm.name,
  695. False))
  696. if self.sort_by_column in ["CPU", "CPU Graph", "MEM", "MEM Graph",
  697. "State", "Size", "Internal"]:
  698. # "State": needed to sort after reload (fill_table sorts items
  699. # with setSortingEnabled, but by that time the widgets values
  700. # are not correct yet).
  701. self.table.sortItems(self.columns_indices[self.sort_by_column],
  702. self.sort_order)
  703. self.table_selection_changed()
  704. self.update_size_on_disk = False
  705. if not out_of_schedule:
  706. self.counter += 1
  707. # noinspection PyCallByClass,PyTypeChecker
  708. QTimer.singleShot(self.update_interval, self.update_table)
  709. def update_block_devices(self):
  710. res, msg = self.blk_manager.check_for_updates()
  711. if msg is not None and len(msg) > 0:
  712. trayIcon.showMessage('\n'.join(msg), msecs=5000)
  713. return res
  714. # noinspection PyPep8Naming
  715. @pyqtSlot(bool, str)
  716. def recAllowedChanged(self, state, vmname):
  717. self.vm_rec[str(vmname)] = bool(state)
  718. def register_dbus_watches(self):
  719. global session_bus
  720. if not session_bus:
  721. session_bus = QDBusConnection.sessionBus()
  722. if not session_bus.connect(QString(), # service
  723. QString(), # path
  724. QString("org.QubesOS.Audio"), # interface
  725. QString("RecAllowedChanged"), # name
  726. self.recAllowedChanged): # slot
  727. print session_bus.lastError().message()
  728. # noinspection PyPep8Naming
  729. def sortIndicatorChanged(self, column, order):
  730. self.sort_by_column = [name for name in self.columns_indices.keys() if
  731. self.columns_indices[name] == column][0]
  732. self.sort_order = order
  733. if self.settings_loaded:
  734. self.manager_settings.setValue('view/sort_column',
  735. self.sort_by_column)
  736. self.manager_settings.setValue('view/sort_order', self.sort_order)
  737. self.manager_settings.sync()
  738. def table_selection_changed(self):
  739. vm = self.get_selected_vm()
  740. if vm is not None:
  741. # Update available actions:
  742. self.action_settings.setEnabled(vm.qid != 0)
  743. self.action_removevm.setEnabled(
  744. not vm.installed_by_rpm and not vm.last_running)
  745. self.action_clonevm.setEnabled(
  746. not vm.last_running and not vm.is_netvm())
  747. self.action_resumevm.setEnabled(not vm.last_running or
  748. vm.last_power_state == "Paused")
  749. try:
  750. self.action_startvm_tools_install.setVisible(
  751. isinstance(vm, QubesHVm))
  752. except NameError:
  753. # ignore non existing QubesHVm
  754. pass
  755. self.action_startvm_tools_install.setEnabled(not vm.last_running)
  756. self.action_pausevm.setEnabled(
  757. vm.last_running and
  758. vm.last_power_state != "Paused" and
  759. vm.qid != 0)
  760. self.action_shutdownvm.setEnabled(
  761. vm.last_running and
  762. vm.last_power_state != "Paused" and
  763. vm.qid != 0)
  764. self.action_restartvm.setEnabled(
  765. vm.last_running and
  766. vm.last_power_state != "Paused" and
  767. vm.qid != 0 and
  768. not vm.is_disposablevm())
  769. self.action_killvm.setEnabled((vm.last_running or
  770. vm.last_power_state == "Paused") and
  771. vm.qid != 0)
  772. self.action_appmenus.setEnabled(vm.qid != 0 and
  773. not vm.internal and
  774. not vm.is_disposablevm())
  775. self.action_editfwrules.setEnabled(vm.is_networked() and not (
  776. vm.is_netvm() and not vm.is_proxyvm()))
  777. self.action_updatevm.setEnabled(vm.is_updateable() or vm.qid == 0)
  778. self.action_toggle_audio_input.setEnabled(
  779. vm.qubes_manager_state[QMVmState.AudioRecAvailable])
  780. self.action_run_command_in_vm.setEnabled(
  781. not vm.last_power_state == "Paused" and vm.qid != 0)
  782. self.action_set_keyboard_layout.setEnabled(
  783. vm.qid != 0 and
  784. vm.last_running and
  785. vm.last_power_state != "Paused")
  786. else:
  787. self.action_settings.setEnabled(False)
  788. self.action_removevm.setEnabled(False)
  789. self.action_startvm_tools_install.setVisible(False)
  790. self.action_startvm_tools_install.setEnabled(False)
  791. self.action_clonevm.setEnabled(False)
  792. self.action_resumevm.setEnabled(False)
  793. self.action_pausevm.setEnabled(False)
  794. self.action_shutdownvm.setEnabled(False)
  795. self.action_restartvm.setEnabled(False)
  796. self.action_killvm.setEnabled(False)
  797. self.action_appmenus.setEnabled(False)
  798. self.action_editfwrules.setEnabled(False)
  799. self.action_updatevm.setEnabled(False)
  800. self.action_toggle_audio_input.setEnabled(False)
  801. self.action_run_command_in_vm.setEnabled(False)
  802. self.action_set_keyboard_layout.setEnabled(False)
  803. def closeEvent(self, event):
  804. # There is something borked in Qt,
  805. # as the logic here is inverted on X11
  806. if event.spontaneous():
  807. self.hide()
  808. event.ignore()
  809. def set_error(self, qid, message):
  810. for vm in self.vms_list:
  811. if vm.qid == qid:
  812. vm.qubes_manager_state[QMVmState.ErrorMsg] = message
  813. # Store error in separate dict to make it immune to VM list reload
  814. self.vm_errors[qid] = str(message)
  815. def clear_error(self, qid):
  816. self.vm_errors.pop(qid, None)
  817. for vm in self.vms_list:
  818. if vm.qid == qid:
  819. vm.qubes_manager_state[QMVmState.ErrorMsg] = None
  820. def clear_error_exact(self, qid, message):
  821. for vm in self.vms_list:
  822. if vm.qid == qid:
  823. if vm.qubes_manager_state[QMVmState.ErrorMsg] == message:
  824. vm.qubes_manager_state[QMVmState.ErrorMsg] = None
  825. self.vm_errors.pop(qid, None)
  826. @pyqtSlot(name='on_action_createvm_triggered')
  827. def action_createvm_triggered(self):
  828. dialog = NewVmDlg(app, self.qvm_collection, trayIcon)
  829. dialog.exec_()
  830. def get_selected_vm(self):
  831. # vm selection relies on the VmInfo widget's value used
  832. # for sorting by VM name
  833. row_index = self.table.currentRow()
  834. if row_index != -1:
  835. vm_item = self.table.item(row_index, self.columns_indices["Name"])
  836. # here is possible race with update_table timer so check
  837. # if really got the item
  838. if vm_item is None:
  839. return None
  840. qid = vm_item.qid
  841. assert self.vms_in_table[qid] is not None
  842. vm = self.vms_in_table[qid].vm
  843. return vm
  844. else:
  845. return None
  846. @pyqtSlot(name='on_action_removevm_triggered')
  847. def action_removevm_triggered(self):
  848. vm = self.get_selected_vm()
  849. assert not vm.is_running()
  850. assert not vm.installed_by_rpm
  851. self.qvm_collection.lock_db_for_reading()
  852. self.qvm_collection.load()
  853. self.qvm_collection.unlock_db()
  854. vm = self.qvm_collection[vm.qid]
  855. if vm.is_template():
  856. dependent_vms = self.qvm_collection.get_vms_based_on(vm.qid)
  857. if len(dependent_vms) > 0:
  858. QMessageBox.warning(
  859. None, "Warning!",
  860. "This Template VM cannot be removed, because there is at "
  861. "least one AppVM that is based on it.<br>"
  862. "<small>If you want to remove this Template VM and all "
  863. "the AppVMs based on it,"
  864. "you should first remove each individual AppVM that uses "
  865. "this template.</small>")
  866. return
  867. (requested_name, ok) = QInputDialog.getText(
  868. None, "VM Removal Confirmation",
  869. "Are you sure you want to remove the VM <b>'{0}'</b>?<br>"
  870. "All data on this VM's private storage will be lost!<br><br>"
  871. "Type the name of the VM (<b>{1}</b>) below to confirm:"
  872. .format(vm.name, vm.name))
  873. if not ok:
  874. # user clicked cancel
  875. return
  876. elif requested_name != vm.name:
  877. # name did not match
  878. QMessageBox.warning(None, "VM removal confirmation failed",
  879. "Entered name did not match! Not removing {0}.".format(vm.name))
  880. return
  881. else:
  882. # remove the VM
  883. thread_monitor = ThreadMonitor()
  884. thread = threading.Thread(target=self.do_remove_vm,
  885. args=(vm, thread_monitor))
  886. thread.daemon = True
  887. thread.start()
  888. progress = QProgressDialog(
  889. "Removing VM: <b>{0}</b>...".format(vm.name), "", 0, 0)
  890. progress.setCancelButton(None)
  891. progress.setModal(True)
  892. progress.show()
  893. while not thread_monitor.is_finished():
  894. app.processEvents()
  895. time.sleep(0.1)
  896. progress.hide()
  897. if thread_monitor.success:
  898. trayIcon.showMessage(
  899. "VM '{0}' has been removed.".format(vm.name), msecs=3000)
  900. else:
  901. QMessageBox.warning(None, "Error removing VM!",
  902. "ERROR: {0}".format(
  903. thread_monitor.error_msg))
  904. @staticmethod
  905. def do_remove_vm(vm, thread_monitor):
  906. qc = QubesVmCollection()
  907. qc.lock_db_for_writing()
  908. try:
  909. qc.load()
  910. vm = qc[vm.qid]
  911. # TODO: the following two conditions should really be checked
  912. # by qvm_collection.pop() overload...
  913. if vm.is_template() and \
  914. qc.default_template_qid == vm.qid:
  915. qc.default_template_qid = None
  916. if vm.is_netvm() and \
  917. qc.default_netvm_qid == vm.qid:
  918. qc.default_netvm_qid = None
  919. qc.pop(vm.qid)
  920. qc.save()
  921. vm.remove_from_disk()
  922. except Exception as ex:
  923. thread_monitor.set_error_msg(str(ex))
  924. finally:
  925. qc.unlock_db()
  926. thread_monitor.set_finished()
  927. @pyqtSlot(name='on_action_clonevm_triggered')
  928. def action_clonevm_triggered(self):
  929. vm = self.get_selected_vm()
  930. name_number = 1
  931. name_format = vm.name + '-clone-%d'
  932. while self.qvm_collection.get_vm_by_name(name_format % name_number):
  933. name_number += 1
  934. (clone_name, ok) = QInputDialog.getText(
  935. self, 'Qubes clone VM',
  936. 'Enter name for VM <b>' + vm.name + '</b> clone:',
  937. text=(name_format % name_number))
  938. if not ok or clone_name == "":
  939. return
  940. thread_monitor = ThreadMonitor()
  941. thread = threading.Thread(target=self.do_clone_vm,
  942. args=(vm, str(clone_name), thread_monitor))
  943. thread.daemon = True
  944. thread.start()
  945. progress = QProgressDialog(
  946. "Cloning VM <b>{0}</b> to <b>{1}</b>...".format(vm.name,
  947. clone_name), "", 0,
  948. 0)
  949. progress.setCancelButton(None)
  950. progress.setModal(True)
  951. progress.show()
  952. while not thread_monitor.is_finished():
  953. app.processEvents()
  954. time.sleep(0.2)
  955. progress.hide()
  956. if not thread_monitor.success:
  957. QMessageBox.warning(None, "Error while cloning VM",
  958. "Exception while cloning:<br>{0}".format(
  959. thread_monitor.error_msg))
  960. @staticmethod
  961. def do_clone_vm(vm, dst_name, thread_monitor):
  962. dst_vm = None
  963. qc = QubesVmCollection()
  964. qc.lock_db_for_writing()
  965. qc.load()
  966. try:
  967. src_vm = qc[vm.qid]
  968. dst_vm = qc.add_new_vm(src_vm.__class__.__name__,
  969. name=dst_name,
  970. template=src_vm.template,
  971. installed_by_rpm=False)
  972. dst_vm.clone_attrs(src_vm)
  973. dst_vm.clone_disk_files(src_vm=src_vm, verbose=False)
  974. qc.save()
  975. except Exception as ex:
  976. if dst_vm:
  977. qc.pop(dst_vm.qid)
  978. dst_vm.remove_from_disk()
  979. thread_monitor.set_error_msg(str(ex))
  980. finally:
  981. qc.unlock_db()
  982. thread_monitor.set_finished()
  983. @pyqtSlot(name='on_action_resumevm_triggered')
  984. def action_resumevm_triggered(self):
  985. vm = self.get_selected_vm()
  986. if vm.get_power_state() in ["Paused", "Suspended"]:
  987. try:
  988. vm.resume()
  989. except Exception as ex:
  990. QMessageBox.warning(None, "Error unpausing VM!",
  991. "ERROR: {0}".format(ex))
  992. return
  993. self.start_vm(vm)
  994. def start_vm(self, vm):
  995. assert not vm.is_running()
  996. thread_monitor = ThreadMonitor()
  997. thread = threading.Thread(target=self.do_start_vm,
  998. args=(vm, thread_monitor))
  999. thread.daemon = True
  1000. thread.start()
  1001. trayIcon.showMessage("Starting '{0}'...".format(vm.name), msecs=3000)
  1002. while not thread_monitor.is_finished():
  1003. app.processEvents()
  1004. time.sleep(0.1)
  1005. if thread_monitor.success:
  1006. trayIcon.showMessage("VM '{0}' has been started.".format(vm.name),
  1007. msecs=3000)
  1008. else:
  1009. trayIcon.showMessage(
  1010. "Error starting VM <b>'{0}'</b>: {1}".format(
  1011. vm.name, thread_monitor.error_msg),
  1012. msecs=3000)
  1013. self.set_error(vm.qid,
  1014. "Error starting VM: %s" % thread_monitor.error_msg)
  1015. @staticmethod
  1016. def do_start_vm(vm, thread_monitor):
  1017. try:
  1018. vm.start()
  1019. except Exception as ex:
  1020. thread_monitor.set_error_msg(str(ex))
  1021. thread_monitor.set_finished()
  1022. return
  1023. thread_monitor.set_finished()
  1024. @pyqtSlot(name='on_action_startvm_tools_install_triggered')
  1025. def action_startvm_tools_install_triggered(self):
  1026. vm = self.get_selected_vm()
  1027. assert not vm.is_running()
  1028. windows_tools_installed = \
  1029. os.path.exists('/usr/lib/qubes/qubes-windows-tools.iso')
  1030. if not windows_tools_installed:
  1031. msg = QMessageBox()
  1032. msg.warning(self, "Error starting VM!",
  1033. "You need to install 'qubes-windows-tools' "
  1034. "package to use this option")
  1035. return
  1036. thread_monitor = ThreadMonitor()
  1037. thread = threading.Thread(target=self.do_start_vm_tools_install,
  1038. args=(vm, thread_monitor))
  1039. thread.daemon = True
  1040. thread.start()
  1041. trayIcon.showMessage("Starting '{0}'...".format(vm.name), msecs=3000)
  1042. while not thread_monitor.is_finished():
  1043. app.processEvents()
  1044. time.sleep(0.1)
  1045. if thread_monitor.success:
  1046. trayIcon.showMessage("VM '{0}' has been started. Start Qubes "
  1047. "Tools installation from attached CD"
  1048. .format(vm.name), msecs=3000)
  1049. else:
  1050. trayIcon.showMessage(
  1051. "Error starting VM <b>'{0}'</b>: {1}"
  1052. .format(vm.name, thread_monitor.error_msg),
  1053. msecs=3000)
  1054. self.set_error(vm.qid,
  1055. "Error starting VM: %s" % thread_monitor.error_msg)
  1056. # noinspection PyMethodMayBeStatic
  1057. def do_start_vm_tools_install(self, vm, thread_monitor):
  1058. prev_drive = vm.drive
  1059. try:
  1060. vm.drive = 'cdrom:dom0:/usr/lib/qubes/qubes-windows-tools.iso'
  1061. vm.start()
  1062. except Exception as ex:
  1063. thread_monitor.set_error_msg(str(ex))
  1064. thread_monitor.set_finished()
  1065. return
  1066. finally:
  1067. vm.drive = prev_drive
  1068. thread_monitor.set_finished()
  1069. @pyqtSlot(name='on_action_pausevm_triggered')
  1070. def action_pausevm_triggered(self):
  1071. vm = self.get_selected_vm()
  1072. assert vm.is_running()
  1073. try:
  1074. vm.pause()
  1075. except Exception as ex:
  1076. QMessageBox.warning(None, "Error pausing VM!",
  1077. "ERROR: {0}".format(ex))
  1078. return
  1079. @pyqtSlot(name='on_action_shutdownvm_triggered')
  1080. def action_shutdownvm_triggered(self):
  1081. vm = self.get_selected_vm()
  1082. assert vm.is_running()
  1083. self.blk_manager.check_if_serves_as_backend(vm)
  1084. reply = QMessageBox.question(
  1085. None, "VM Shutdown Confirmation",
  1086. "Are you sure you want to power down the VM <b>'{0}'</b>?<br>"
  1087. "<small>This will shutdown all the running applications "
  1088. "within this VM.</small>".format(vm.name),
  1089. QMessageBox.Yes | QMessageBox.Cancel)
  1090. app.processEvents()
  1091. if reply == QMessageBox.Yes:
  1092. self.shutdown_vm(vm)
  1093. def shutdown_vm(self, vm, shutdown_time=vm_shutdown_timeout,
  1094. check_time=vm_restart_check_timeout, and_restart=False):
  1095. try:
  1096. vm.shutdown()
  1097. except Exception as ex:
  1098. QMessageBox.warning(None, "Error shutting down VM!",
  1099. "ERROR: {0}".format(ex))
  1100. return
  1101. trayIcon.showMessage("VM '{0}' is shutting down...".format(vm.name),
  1102. msecs=3000)
  1103. self.shutdown_monitor[vm.qid] = VmShutdownMonitor(vm, shutdown_time,
  1104. check_time, and_restart, self)
  1105. # noinspection PyCallByClass,PyTypeChecker
  1106. QTimer.singleShot(check_time, self.shutdown_monitor[
  1107. vm.qid].check_if_vm_has_shutdown)
  1108. @pyqtSlot(name='on_action_restartvm_triggered')
  1109. def action_restartvm_triggered(self):
  1110. vm = self.get_selected_vm()
  1111. assert vm.is_running()
  1112. self.blk_manager.check_if_serves_as_backend(vm)
  1113. reply = QMessageBox.question(
  1114. None, "VM Restart Confirmation",
  1115. "Are you sure you want to restart the VM <b>'{0}'</b>?<br>"
  1116. "<small>This will shutdown all the running applications "
  1117. "within this VM.</small>".format(vm.name),
  1118. QMessageBox.Yes | QMessageBox.Cancel)
  1119. app.processEvents()
  1120. if reply == QMessageBox.Yes:
  1121. self.shutdown_vm(vm, and_restart=True)
  1122. @pyqtSlot(name='on_action_killvm_triggered')
  1123. def action_killvm_triggered(self):
  1124. vm = self.get_selected_vm()
  1125. assert vm.is_running() or vm.is_paused()
  1126. reply = QMessageBox.question(
  1127. None, "VM Kill Confirmation",
  1128. "Are you sure you want to kill the VM <b>'{0}'</b>?<br>"
  1129. "<small>This will end <b>(not shutdown!)</b> all the running "
  1130. "applications within this VM.</small>".format(vm.name),
  1131. QMessageBox.Yes | QMessageBox.Cancel,
  1132. QMessageBox.Cancel)
  1133. app.processEvents()
  1134. if reply == QMessageBox.Yes:
  1135. try:
  1136. vm.force_shutdown()
  1137. except Exception as ex:
  1138. QMessageBox.critical(
  1139. None, "Error while killing VM!",
  1140. "<b>An exception ocurred while killing {0}.</b><br>"
  1141. "ERROR: {1}".format(vm.name, ex))
  1142. return
  1143. trayIcon.showMessage("VM '{0}' killed!".format(vm.name), msecs=3000)
  1144. @pyqtSlot(name='on_action_settings_triggered')
  1145. def action_settings_triggered(self):
  1146. vm = self.get_selected_vm()
  1147. settings_window = VMSettingsWindow(vm, app, self.qvm_collection,
  1148. "basic")
  1149. settings_window.exec_()
  1150. @pyqtSlot(name='on_action_appmenus_triggered')
  1151. def action_appmenus_triggered(self):
  1152. vm = self.get_selected_vm()
  1153. settings_window = VMSettingsWindow(vm, app, self.qvm_collection,
  1154. "applications")
  1155. settings_window.exec_()
  1156. def update_audio_rec_info(self, vm):
  1157. vm.qubes_manager_state[QMVmState.AudioRecAvailable] = (
  1158. session_bus.interface().isServiceRegistered(
  1159. 'org.QubesOS.Audio.%s' % vm.name).value())
  1160. if vm.qubes_manager_state[QMVmState.AudioRecAvailable]:
  1161. vm.qubes_manager_state[
  1162. QMVmState.AudioRecAllowed] = self.get_audio_rec_allowed(vm.name)
  1163. else:
  1164. vm.qubes_manager_state[QMVmState.AudioRecAllowed] = False
  1165. # noinspection PyMethodMayBeStatic
  1166. def get_audio_rec_allowed(self, vmname):
  1167. properties = QDBusInterface('org.QubesOS.Audio.%s' % vmname,
  1168. '/org/qubesos/audio',
  1169. 'org.freedesktop.DBus.Properties',
  1170. session_bus)
  1171. current_audio = properties.call('Get', 'org.QubesOS.Audio',
  1172. 'RecAllowed')
  1173. if current_audio.type() == current_audio.ReplyMessage:
  1174. value = current_audio.arguments()[0].toPyObject().toBool()
  1175. return bool(value)
  1176. return False
  1177. @pyqtSlot(name='on_action_toggle_audio_input_triggered')
  1178. def action_toggle_audio_input_triggered(self):
  1179. vm = self.get_selected_vm()
  1180. properties = QDBusInterface('org.QubesOS.Audio.%s' % vm.name,
  1181. '/org/qubesos/audio',
  1182. 'org.freedesktop.DBus.Properties',
  1183. session_bus)
  1184. properties.call('Set', 'org.QubesOS.Audio', 'RecAllowed',
  1185. QDBusVariant(not self.get_audio_rec_allowed(vm.name)))
  1186. # icon will be updated based on dbus signal
  1187. @pyqtSlot(name='on_action_updatevm_triggered')
  1188. def action_updatevm_triggered(self):
  1189. vm = self.get_selected_vm()
  1190. if not vm.is_running():
  1191. reply = QMessageBox.question(
  1192. None, "VM Update Confirmation",
  1193. "<b>{0}</b><br>The VM has to be running to be updated.<br>"
  1194. "Do you want to start it?<br>".format(vm.name),
  1195. QMessageBox.Yes | QMessageBox.Cancel)
  1196. if reply != QMessageBox.Yes:
  1197. return
  1198. trayIcon.showMessage("Starting '{0}'...".format(vm.name),
  1199. msecs=3000)
  1200. app.processEvents()
  1201. thread_monitor = ThreadMonitor()
  1202. thread = threading.Thread(target=self.do_update_vm,
  1203. args=(vm, thread_monitor))
  1204. thread.daemon = True
  1205. thread.start()
  1206. progress = QProgressDialog(
  1207. "<b>{0}</b><br>Please wait for the updater to launch...".format(
  1208. vm.name), "", 0, 0)
  1209. progress.setCancelButton(None)
  1210. progress.setModal(True)
  1211. progress.show()
  1212. while not thread_monitor.is_finished():
  1213. app.processEvents()
  1214. time.sleep(0.2)
  1215. progress.hide()
  1216. if vm.qid != 0:
  1217. if not thread_monitor.success:
  1218. QMessageBox.warning(None, "Error VM update!",
  1219. "ERROR: {0}".format(
  1220. thread_monitor.error_msg))
  1221. @staticmethod
  1222. def do_update_vm(vm, thread_monitor):
  1223. try:
  1224. if vm.qid == 0:
  1225. subprocess.check_call(
  1226. ["/usr/bin/qubes-dom0-update", "--clean", "--gui"])
  1227. else:
  1228. if not vm.is_running():
  1229. trayIcon.showMessage(
  1230. "Starting the '{0}' VM...".format(vm.name),
  1231. msecs=3000)
  1232. vm.start()
  1233. vm.run_service("qubes.InstallUpdatesGUI", gui=True,
  1234. wait=False)
  1235. except Exception as ex:
  1236. thread_monitor.set_error_msg(str(ex))
  1237. thread_monitor.set_finished()
  1238. return
  1239. thread_monitor.set_finished()
  1240. @pyqtSlot(name='on_action_run_command_in_vm_triggered')
  1241. def action_run_command_in_vm_triggered(self):
  1242. vm = self.get_selected_vm()
  1243. (command_to_run, ok) = QInputDialog.getText(
  1244. self, 'Qubes command entry',
  1245. 'Run command in <b>' + vm.name + '</b>:')
  1246. if not ok or command_to_run == "":
  1247. return
  1248. thread_monitor = ThreadMonitor()
  1249. thread = threading.Thread(target=self.do_run_command_in_vm, args=(
  1250. vm, unicode(command_to_run), thread_monitor))
  1251. thread.daemon = True
  1252. thread.start()
  1253. while not thread_monitor.is_finished():
  1254. app.processEvents()
  1255. time.sleep(0.2)
  1256. if not thread_monitor.success:
  1257. QMessageBox.warning(None, "Error while running command",
  1258. "Exception while running command:<br>{0}".format(
  1259. thread_monitor.error_msg))
  1260. @staticmethod
  1261. def do_run_command_in_vm(vm, command_to_run, thread_monitor):
  1262. try:
  1263. vm.run(command_to_run, verbose=False, autostart=True,
  1264. notify_function=lambda lvl, msg: trayIcon.showMessage(
  1265. msg, msecs=3000))
  1266. except Exception as ex:
  1267. thread_monitor.set_error_msg(str(ex))
  1268. thread_monitor.set_finished()
  1269. @pyqtSlot(name='on_action_set_keyboard_layout_triggered')
  1270. def action_set_keyboard_layout_triggered(self):
  1271. vm = self.get_selected_vm()
  1272. vm.run('qubes-change-keyboard-layout', verbose=False)
  1273. @pyqtSlot(name='on_action_showallvms_triggered')
  1274. def action_showallvms_triggered(self):
  1275. self.show_inactive_vms = self.action_showallvms.isChecked()
  1276. self.showhide_vms()
  1277. self.set_table_geom_size()
  1278. if self.settings_loaded:
  1279. self.manager_settings.setValue('view/show_inactive_vms',
  1280. self.show_inactive_vms)
  1281. self.manager_settings.sync()
  1282. @pyqtSlot(name='on_action_showinternalvms_triggered')
  1283. def action_showinternalvms_triggered(self):
  1284. self.show_internal_vms = self.action_showinternalvms.isChecked()
  1285. self.showhide_vms()
  1286. self.set_table_geom_size()
  1287. if self.settings_loaded:
  1288. self.manager_settings.setValue('view/show_internal_vms',
  1289. self.show_internal_vms)
  1290. self.manager_settings.sync()
  1291. @pyqtSlot(name='on_action_editfwrules_triggered')
  1292. def action_editfwrules_triggered(self):
  1293. vm = self.get_selected_vm()
  1294. settings_window = VMSettingsWindow(vm, app, self.qvm_collection,
  1295. "firewall")
  1296. settings_window.exec_()
  1297. @pyqtSlot(name='on_action_global_settings_triggered')
  1298. def action_global_settings_triggered(self):
  1299. global_settings_window = GlobalSettingsWindow(app, self.qvm_collection)
  1300. global_settings_window.exec_()
  1301. @pyqtSlot(name='on_action_restore_triggered')
  1302. def action_restore_triggered(self):
  1303. restore_window = RestoreVMsWindow(app, self.qvm_collection,
  1304. self.blk_manager)
  1305. restore_window.exec_()
  1306. @pyqtSlot(name='on_action_backup_triggered')
  1307. def action_backup_triggered(self):
  1308. backup_window = BackupVMsWindow(app, self.qvm_collection,
  1309. self.blk_manager, self.shutdown_vm)
  1310. backup_window.exec_()
  1311. def showhide_menubar(self, checked):
  1312. self.menubar.setVisible(checked)
  1313. self.set_table_geom_size()
  1314. if not checked:
  1315. self.context_menu.addAction(self.action_menubar)
  1316. else:
  1317. self.context_menu.removeAction(self.action_menubar)
  1318. if self.settings_loaded:
  1319. self.manager_settings.setValue('view/menubar_visible', checked)
  1320. self.manager_settings.sync()
  1321. def showhide_toolbar(self, checked):
  1322. self.toolbar.setVisible(checked)
  1323. self.set_table_geom_size()
  1324. if not checked:
  1325. self.context_menu.addAction(self.action_toolbar)
  1326. else:
  1327. self.context_menu.removeAction(self.action_toolbar)
  1328. if self.settings_loaded:
  1329. self.manager_settings.setValue('view/toolbar_visible', checked)
  1330. self.manager_settings.sync()
  1331. def showhide_column(self, col_num, show):
  1332. self.table.setColumnHidden(col_num, not show)
  1333. self.set_table_geom_size()
  1334. val = 1 if show else -1
  1335. self.visible_columns_count += val
  1336. if self.visible_columns_count == 1:
  1337. # disable hiding the last one
  1338. for c in self.columns_actions:
  1339. if self.columns_actions[c].isChecked():
  1340. self.columns_actions[c].setEnabled(False)
  1341. break
  1342. elif self.visible_columns_count == 2 and val == 1:
  1343. # enable hiding previously disabled column
  1344. for c in self.columns_actions:
  1345. if not self.columns_actions[c].isEnabled():
  1346. self.columns_actions[c].setEnabled(True)
  1347. break
  1348. if self.settings_loaded:
  1349. col_name = [name for name in self.columns_indices.keys() if
  1350. self.columns_indices[name] == col_num][0]
  1351. self.manager_settings.setValue('columns/%s' % col_name, show)
  1352. self.manager_settings.sync()
  1353. def on_action_vm_type_toggled(self, checked):
  1354. self.showhide_column(self.columns_indices['Type'], checked)
  1355. def on_action_label_toggled(self, checked):
  1356. self.showhide_column(self.columns_indices['Label'], checked)
  1357. def on_action_name_toggled(self, checked):
  1358. self.showhide_column(self.columns_indices['Name'], checked)
  1359. def on_action_state_toggled(self, checked):
  1360. self.showhide_column(self.columns_indices['State'], checked)
  1361. def on_action_internal_toggled(self, checked):
  1362. self.showhide_column(self.columns_indices['Internal'], checked)
  1363. def on_action_ip_toggled(self, checked):
  1364. self.showhide_column(self.columns_indices['IP'], checked)
  1365. def on_action_backups_toggled(self, checked):
  1366. self.showhide_column(self.columns_indices['Backups'], checked)
  1367. def on_action_last_backup_toggled(self, checked):
  1368. self.showhide_column(self.columns_indices['Last backup'], checked)
  1369. def on_action_template_toggled(self, checked):
  1370. self.showhide_column(self.columns_indices['Template'], checked)
  1371. def on_action_netvm_toggled(self, checked):
  1372. self.showhide_column(self.columns_indices['NetVM'], checked)
  1373. def on_action_cpu_toggled(self, checked):
  1374. self.showhide_column(self.columns_indices['CPU'], checked)
  1375. def on_action_cpu_graph_toggled(self, checked):
  1376. self.showhide_column(self.columns_indices['CPU Graph'], checked)
  1377. def on_action_mem_toggled(self, checked):
  1378. self.showhide_column(self.columns_indices['MEM'], checked)
  1379. def on_action_mem_graph_toggled(self, checked):
  1380. self.showhide_column(self.columns_indices['MEM Graph'], checked)
  1381. def on_action_size_on_disk_toggled(self, checked):
  1382. self.showhide_column(self.columns_indices['Size'], checked)
  1383. @pyqtSlot(name='on_action_about_qubes_triggered')
  1384. def action_about_qubes_triggered(self):
  1385. about = AboutDialog()
  1386. about.exec_()
  1387. def createPopupMenu(self):
  1388. menu = QMenu()
  1389. menu.addAction(self.action_toolbar)
  1390. menu.addAction(self.action_menubar)
  1391. return menu
  1392. def open_tools_context_menu(self, widget, point):
  1393. self.tools_context_menu.exec_(widget.mapToGlobal(point))
  1394. @pyqtSlot('const QPoint&')
  1395. def open_context_menu(self, point):
  1396. vm = self.get_selected_vm()
  1397. running = vm.is_running()
  1398. # logs menu
  1399. self.logs_menu.clear()
  1400. if vm.qid == 0:
  1401. logfiles = ["/var/log/xen/console/hypervisor.log"]
  1402. else:
  1403. logfiles = [
  1404. "/var/log/xen/console/guest-" + vm.name + ".log",
  1405. "/var/log/xen/console/guest-" + vm.name + "-dm.log",
  1406. "/var/log/qubes/guid." + vm.name + ".log",
  1407. "/var/log/qubes/qrexec." + vm.name + ".log",
  1408. ]
  1409. menu_empty = True
  1410. for logfile in logfiles:
  1411. if os.path.exists(logfile):
  1412. action = self.logs_menu.addAction(QIcon(":/log.png"), logfile)
  1413. action.setData(QVariant(logfile))
  1414. menu_empty = False
  1415. self.logs_menu.setEnabled(not menu_empty)
  1416. # blk menu
  1417. if not running:
  1418. self.blk_menu.setEnabled(False)
  1419. else:
  1420. self.blk_menu.clear()
  1421. self.blk_menu.setEnabled(True)
  1422. self.blk_manager.blk_lock.acquire()
  1423. if len(self.blk_manager.attached_devs) > 0:
  1424. for d in self.blk_manager.attached_devs:
  1425. if (self.blk_manager.attached_devs[d]
  1426. ['attached_to']['vm'].qid == vm.qid):
  1427. text = "Detach " + d + " " + unicode(
  1428. self.blk_manager.attached_devs[d]['size']) + " " + \
  1429. self.blk_manager.attached_devs[d]['desc']
  1430. action = self.blk_menu.addAction(QIcon(":/remove.png"),
  1431. text)
  1432. action.setData(QVariant(d))
  1433. if len(self.blk_manager.free_devs) > 0:
  1434. for d in self.blk_manager.free_devs:
  1435. if d.startswith(vm.name):
  1436. continue
  1437. # skip partitions heuristic
  1438. if d[-1].isdigit() and \
  1439. d[0:-1] in self.blk_manager.current_blk:
  1440. continue
  1441. text = "Attach " + d + " " + unicode(
  1442. self.blk_manager.free_devs[d]['size']) + " " + \
  1443. self.blk_manager.free_devs[d]['desc']
  1444. action = self.blk_menu.addAction(QIcon(":/add.png"), text)
  1445. action.setData(QVariant(d))
  1446. self.blk_manager.blk_lock.release()
  1447. if self.blk_menu.isEmpty():
  1448. self.blk_menu.setEnabled(False)
  1449. self.context_menu.exec_(self.table.mapToGlobal(point))
  1450. @pyqtSlot('QAction *')
  1451. def show_log(self, action):
  1452. log = str(action.data().toString())
  1453. log_dialog = LogDialog(app, log)
  1454. log_dialog.exec_()
  1455. @pyqtSlot('QAction *')
  1456. def attach_dettach_device_triggered(self, action):
  1457. dev = str(action.data().toString())
  1458. vm = self.get_selected_vm()
  1459. self.blk_manager.blk_lock.acquire()
  1460. try:
  1461. if dev in self.blk_manager.attached_devs:
  1462. self.blk_manager.detach_device(vm, dev)
  1463. else:
  1464. self.blk_manager.attach_device(vm, dev)
  1465. self.blk_manager.blk_lock.release()
  1466. except QubesException as e:
  1467. self.blk_manager.blk_lock.release()
  1468. QMessageBox.critical(None, "Block attach/detach error!", str(e))
  1469. class QubesTrayIcon(QSystemTrayIcon):
  1470. def __init__(self, icon, blk_manager):
  1471. QSystemTrayIcon.__init__(self, icon)
  1472. self.menu = QMenu()
  1473. action_showmanager = self.create_action("Open VM Manager",
  1474. slot=show_manager, icon="qubes")
  1475. action_backup = self.create_action("Make backup")
  1476. action_preferences = self.create_action("Preferences")
  1477. action_set_netvm = self.create_action("Set default NetVM",
  1478. icon="networking")
  1479. action_sys_info = self.create_action("System Info", icon="dom0")
  1480. action_exit = self.create_action("Exit", slot=exit_app)
  1481. action_backup.setDisabled(True)
  1482. action_preferences.setDisabled(True)
  1483. action_set_netvm.setDisabled(True)
  1484. action_sys_info.setDisabled(True)
  1485. self.blk_manager = blk_manager
  1486. self.blk_menu = QMenu(self.menu)
  1487. self.blk_menu.setTitle("Block devices")
  1488. action_blk_menu = self.create_action("Block devices")
  1489. action_blk_menu.setMenu(self.blk_menu)
  1490. self.add_actions(self.menu, (action_showmanager,
  1491. action_blk_menu,
  1492. action_backup,
  1493. action_sys_info,
  1494. None,
  1495. action_preferences,
  1496. action_set_netvm,
  1497. None,
  1498. action_exit))
  1499. self.setContextMenu(self.menu)
  1500. self.connect(self,
  1501. SIGNAL("activated (QSystemTrayIcon::ActivationReason)"),
  1502. self.icon_clicked)
  1503. self.tray_notifier_type = None
  1504. self.tray_notifier = QDBusInterface("org.freedesktop.Notifications",
  1505. "/org/freedesktop/Notifications",
  1506. "org.freedesktop.Notifications",
  1507. session_bus)
  1508. srv_info = self.tray_notifier.call("GetServerInformation")
  1509. if srv_info.type() == QDBusMessage.ReplyMessage and \
  1510. len(srv_info.arguments()) > 1:
  1511. self.tray_notifier_type = srv_info.arguments()[1]
  1512. if os.path.exists(table_widgets.qubes_dom0_updates_stat_file):
  1513. self.showMessage("Qubes dom0 updates available.", msecs=0)
  1514. def update_blk_menu(self):
  1515. global manager_window
  1516. def create_vm_submenu(dev):
  1517. blk_vm_menu = QMenu(self.blk_menu)
  1518. blk_vm_menu.triggered.connect(
  1519. lambda a, trig_dev=dev: self.attach_device_triggered(a,
  1520. trig_dev))
  1521. for this_vm in sorted(manager_window.qvm_collection.values(),
  1522. key=lambda x: x.name):
  1523. if not this_vm.is_running():
  1524. continue
  1525. if this_vm.qid == 0:
  1526. # skip dom0 to prevent (fatal) mistakes
  1527. continue
  1528. this_action = blk_vm_menu.addAction(QIcon(":/add.png"),
  1529. this_vm.name)
  1530. this_action.setData(QVariant(this_vm))
  1531. return blk_vm_menu
  1532. self.blk_menu.clear()
  1533. self.blk_menu.setEnabled(True)
  1534. self.blk_manager.blk_lock.acquire()
  1535. if len(self.blk_manager.attached_devs) > 0:
  1536. for d in self.blk_manager.attached_devs:
  1537. vm = self.blk_manager.attached_devs[d]['attached_to']['vm']
  1538. text = "Detach %s %s (%s) from %s" % (
  1539. d,
  1540. self.blk_manager.attached_devs[d]['desc'],
  1541. unicode(self.blk_manager.attached_devs[d]['size']),
  1542. vm.name)
  1543. action = self.blk_menu.addAction(QIcon(":/remove.png"), text)
  1544. action.setData(QVariant(d))
  1545. action.triggered.connect(
  1546. lambda b, a=action: self.dettach_device_triggered(a))
  1547. if len(self.blk_manager.free_devs) > 0:
  1548. for d in self.blk_manager.free_devs:
  1549. # skip partitions heuristic
  1550. if d[-1].isdigit() and d[0:-1] in self.blk_manager.current_blk:
  1551. continue
  1552. text = "Attach %s %s %s" % (
  1553. d,
  1554. unicode(self.blk_manager.free_devs[d]['size']),
  1555. self.blk_manager.free_devs[d]['desc']
  1556. )
  1557. action = self.blk_menu.addAction(QIcon(":/add.png"), text)
  1558. action.setMenu(create_vm_submenu(d))
  1559. self.blk_manager.blk_lock.release()
  1560. if self.blk_menu.isEmpty():
  1561. self.blk_menu.setEnabled(False)
  1562. @pyqtSlot('QAction *')
  1563. def attach_device_triggered(self, action, dev):
  1564. vm = action.data().toPyObject()
  1565. self.blk_manager.blk_lock.acquire()
  1566. try:
  1567. self.blk_manager.attach_device(vm, dev)
  1568. self.blk_manager.blk_lock.release()
  1569. except QubesException as e:
  1570. self.blk_manager.blk_lock.release()
  1571. QMessageBox.critical(None, "Block attach/detach error!", str(e))
  1572. @pyqtSlot('QAction *')
  1573. def dettach_device_triggered(self, action):
  1574. dev = str(action.data().toString())
  1575. vm = self.blk_manager.attached_devs[dev]['attached_to']['vm']
  1576. self.blk_manager.blk_lock.acquire()
  1577. try:
  1578. self.blk_manager.detach_device(vm, dev)
  1579. self.blk_manager.blk_lock.release()
  1580. except QubesException as e:
  1581. self.blk_manager.blk_lock.release()
  1582. QMessageBox.critical(None, "Block attach/detach error!", str(e))
  1583. def icon_clicked(self, reason):
  1584. if reason == QSystemTrayIcon.Context:
  1585. self.update_blk_menu()
  1586. # Handle the right click normally, i.e. display the context menu
  1587. return
  1588. else:
  1589. bring_manager_to_front()
  1590. # noinspection PyMethodMayBeStatic
  1591. def add_actions(self, target, actions):
  1592. for action in actions:
  1593. if action is None:
  1594. target.addSeparator()
  1595. else:
  1596. target.addAction(action)
  1597. def showMessage(self, message, msecs, **kwargs):
  1598. # QtDBus bindings doesn't use introspection to get proper method
  1599. # parameters types, so must cast explicitly
  1600. v_replace_id = QVariant(0)
  1601. v_replace_id.convert(QVariant.UInt)
  1602. v_actions = QVariant([])
  1603. v_actions.convert(QVariant.StringList)
  1604. if self.tray_notifier_type == "KDE":
  1605. message = message.replace('\n', '<br/>\n')
  1606. self.tray_notifier.call("Notify", "Qubes", v_replace_id,
  1607. "qubes-manager", "Qubes VM Manager",
  1608. message, v_actions, QVariant.fromMap({}), msecs)
  1609. def create_action(self, text, slot=None, shortcut=None, icon=None,
  1610. tip=None, checkable=False, signal="triggered()"):
  1611. action = QAction(text, self)
  1612. if icon is not None:
  1613. action.setIcon(QIcon(":/%s.png" % icon))
  1614. if shortcut is not None:
  1615. action.setShortcut(shortcut)
  1616. if tip is not None:
  1617. action.setToolTip(tip)
  1618. action.setStatusTip(tip)
  1619. if slot is not None:
  1620. self.connect(action, SIGNAL(signal), slot)
  1621. if checkable:
  1622. action.setCheckable(True)
  1623. return action
  1624. class QubesDbusNotifyServerAdaptor(QDBusAbstractAdaptor):
  1625. """ This provides the DBus adaptor to the outside world"""
  1626. Q_CLASSINFO("D-Bus Interface", dbus_interface)
  1627. @pyqtSlot(str, str)
  1628. def notify_error(self, vmname, message):
  1629. vm = self.parent().qvm_collection.get_vm_by_name(vmname)
  1630. if vm:
  1631. self.parent().set_error(vm.qid, message)
  1632. else:
  1633. # ignore VM-not-found error
  1634. pass
  1635. @pyqtSlot(str, str)
  1636. def clear_error_exact(self, vmname, message):
  1637. vm = self.parent().qvm_collection.get_vm_by_name(vmname)
  1638. if vm:
  1639. self.parent().clear_error_exact(vm.qid, message)
  1640. else:
  1641. # ignore VM-not-found error
  1642. pass
  1643. @pyqtSlot(str)
  1644. def clear_error(self, vmname):
  1645. vm = self.parent().qvm_collection.get_vm_by_name(vmname)
  1646. if vm:
  1647. self.parent().clear_error(vm.qid)
  1648. else:
  1649. # ignore VM-not-found error
  1650. pass
  1651. @pyqtSlot()
  1652. def show_manager(self):
  1653. bring_manager_to_front()
  1654. def get_frame_size():
  1655. w = 0
  1656. h = 0
  1657. cmd = ['/usr/bin/xprop', '-name', 'Qubes VM Manager', '|', 'grep',
  1658. '_NET_FRAME_EXTENTS']
  1659. xprop = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  1660. for l in xprop.stdout:
  1661. line = l.split('=')
  1662. if len(line) == 2:
  1663. line = line[1].strip().split(',')
  1664. if len(line) == 4:
  1665. w = int(line[0].strip()) + int(line[1].strip())
  1666. h = int(line[2].strip()) + int(line[3].strip())
  1667. break
  1668. # in case of some weird window managers we have to assume sth...
  1669. if w <= 0:
  1670. w = 10
  1671. if h <= 0:
  1672. h = 30
  1673. manager_window.frame_width = w
  1674. manager_window.frame_height = h
  1675. return
  1676. def show_manager():
  1677. manager_window.show()
  1678. manager_window.set_table_geom_size()
  1679. manager_window.repaint()
  1680. manager_window.update_table(out_of_schedule=True)
  1681. app.processEvents()
  1682. get_frame_size()
  1683. # print manager_window.frame_width, " x ", manager_window.frame_height
  1684. manager_window.set_table_geom_size()
  1685. def bring_manager_to_front():
  1686. if manager_window.isVisible():
  1687. subprocess.check_call(
  1688. ['/usr/bin/wmctrl', '-R', str(manager_window.windowTitle())])
  1689. else:
  1690. show_manager()
  1691. def show_running_manager_via_dbus():
  1692. global system_bus
  1693. if system_bus is None:
  1694. system_bus = QDBusConnection.systemBus()
  1695. qubes_manager = QDBusInterface('org.qubesos.QubesManager',
  1696. '/org/qubesos/QubesManager',
  1697. 'org.qubesos.QubesManager', system_bus)
  1698. qubes_manager.call('show_manager')
  1699. def exit_app():
  1700. notifier.stop()
  1701. app.exit()
  1702. # Bases on the original code by:
  1703. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  1704. def handle_exception(exc_type, exc_value, exc_traceback):
  1705. import os.path
  1706. import traceback
  1707. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  1708. filename = os.path.basename(filename)
  1709. error = "%s: %s" % (exc_type.__name__, exc_value)
  1710. error = error.replace('QubesException: ', '')
  1711. message = (
  1712. "<b>%s</b>" % error +
  1713. "<br><br><i>This is most likely a bug in the Qubes Manager</i>"
  1714. )
  1715. is_gui_thread = threading.currentThread().getName() == "QtMainThread"
  1716. strace = ""
  1717. stacktrace = traceback.extract_tb(exc_traceback)
  1718. while len(stacktrace) > 0:
  1719. (filename, line, func, txt) = stacktrace.pop()
  1720. strace += "----\n"
  1721. strace += "line: %s\n" % txt
  1722. strace += "func: %s\n" % func
  1723. strace += "line no.: %d\n" % line
  1724. strace += "file: %s\n" % filename
  1725. if is_gui_thread:
  1726. msg_box = QMessageBox()
  1727. msg_box.setDetailedText(strace)
  1728. msg_box.setIcon(QMessageBox.Critical)
  1729. msg_box.setWindowTitle("Houston, we have a problem...")
  1730. msg_box.setText(message)
  1731. msg_box.exec_()
  1732. else:
  1733. print >>sys.stderr, message
  1734. def sighup_handler(signum, frame):
  1735. os.execl("/usr/bin/qubes-manager", "qubes-manager")
  1736. def main():
  1737. signal.signal(signal.SIGHUP, sighup_handler)
  1738. global system_bus
  1739. system_bus = QDBusConnection.systemBus()
  1740. # Avoid starting more than one instance of the app
  1741. if not system_bus.registerService('org.qubesos.QubesManager'):
  1742. show_running_manager_via_dbus()
  1743. return
  1744. global qubes_host
  1745. qubes_host = QubesHost()
  1746. global app
  1747. app = QApplication(sys.argv)
  1748. app.setOrganizationName("The Qubes Project")
  1749. app.setOrganizationDomain("http://qubes-os.org")
  1750. app.setApplicationName("Qubes VM Manager")
  1751. app.setWindowIcon(QIcon.fromTheme("qubes-manager"))
  1752. app.setAttribute(Qt.AA_DontShowIconsInMenus, False)
  1753. sys.excepthook = handle_exception
  1754. global session_bus
  1755. session_bus = QDBusConnection.sessionBus()
  1756. qvm_collection = QubesVmCollection()
  1757. qvm_collection.lock_db_for_reading()
  1758. qvm_collection.load()
  1759. qvm_collection.unlock_db()
  1760. blk_manager = QubesBlockDevicesManager(qvm_collection)
  1761. global trayIcon
  1762. trayIcon = QubesTrayIcon(QIcon.fromTheme("qubes-manager"), blk_manager)
  1763. global manager_window
  1764. manager_window = VmManagerWindow(qvm_collection, blk_manager)
  1765. global wm
  1766. wm = WatchManager()
  1767. global notifier
  1768. notifier = ThreadedNotifier(wm, QubesManagerFileWatcher(
  1769. manager_window.mark_table_for_update))
  1770. notifier.start()
  1771. wm.add_watch(system_path["qubes_store_filename"],
  1772. EventsCodes.OP_FLAGS.get('IN_MODIFY'))
  1773. wm.add_watch(os.path.dirname(system_path["qubes_store_filename"]),
  1774. EventsCodes.OP_FLAGS.get('IN_MOVED_TO'))
  1775. if os.path.exists(qubes_clipboard_info_file):
  1776. wm.add_watch(qubes_clipboard_info_file,
  1777. EventsCodes.OP_FLAGS.get('IN_CLOSE_WRITE'))
  1778. wm.add_watch(os.path.dirname(qubes_clipboard_info_file),
  1779. EventsCodes.OP_FLAGS.get('IN_CREATE'))
  1780. wm.add_watch(os.path.dirname(table_widgets.qubes_dom0_updates_stat_file),
  1781. EventsCodes.OP_FLAGS.get('IN_CREATE'))
  1782. system_bus.registerObject(dbus_object_path, manager_window)
  1783. threading.currentThread().setName("QtMainThread")
  1784. trayIcon.show()
  1785. show_manager()
  1786. app.exec_()
  1787. trayIcon = None
  1788. if __name__ == "__main__":
  1789. main()