main.py 82 KB

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