main.py 76 KB

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