main.py 84 KB

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