main.py 71 KB

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