main.py 83 KB

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