main.py 85 KB

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