main.py 84 KB

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