main.py 84 KB

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