main.py 71 KB

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