main.py 84 KB

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