main.py 84 KB

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