main.py 83 KB

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