-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathqube_manager.py
1754 lines (1502 loc) · 68.2 KB
/
qube_manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2012 Agnieszka Kostrzewa <[email protected]>
# Copyright (C) 2012 Marek Marczykowski-Górecki
# Copyright (C) 2017 Wojtek Porczyk <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program; if not, see <http://www.gnu.org/licenses/>.
#
#
import subprocess
from datetime import datetime, timedelta
from functools import partial
from os import path
from qubesadmin import exc
from qubesadmin import utils
# pylint: disable=import-error
from PyQt5.QtCore import (Qt, QAbstractTableModel, QObject, pyqtSlot, QEvent,
QSettings, QRegExp, QSortFilterProxyModel, QSize, QPoint, QTimer)
# pylint: disable=import-error
from PyQt5.QtWidgets import (QLineEdit, QStyledItemDelegate, QToolTip,
QMenu, QInputDialog, QMainWindow, QProgressDialog, QStyleOptionViewItem,
QMessageBox)
# pylint: disable=import-error
from PyQt5.QtGui import (QIcon, QPixmap, QRegExpValidator, QFont, QColor)
from qubesmanager.about import AboutDialog
from . import ui_qubemanager # pylint: disable=no-name-in-module
from . import settings
from . import global_settings
from . import restore
from . import backup
from . import create_new_vm
from . import log_dialog
from . import utils as manager_utils
from . import common_threads
from . import clone_vm
class SearchBox(QLineEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.focusing = False
def focusInEvent(self, e): # pylint: disable=invalid-name
super().focusInEvent(e)
self.selectAll()
self.focusing = True
def mousePressEvent(self, e): # pylint: disable=invalid-name
super().mousePressEvent(e)
if self.focusing:
self.selectAll()
self.focusing = False
icon_size = QSize(22, 22)
# pylint: disable=invalid-name
class StateIconDelegate(QStyledItemDelegate):
lastIndex = None
def __init__(self):
super().__init__()
self.stateIcons = {
"Running" : QIcon(":/on.png"),
"Paused" : QIcon(":/paused.png"),
"Suspended" : QIcon(":/paused.png"),
"Transient" : QIcon(":/transient.png"),
"Halting" : QIcon(":/transient.png"),
"Dying" : QIcon(":/transient.png"),
"Halted" : QIcon(":/off.png")
}
self.outdatedIcons = {
"update" : QIcon(":/update-recommended.png"),
"outdated" : QIcon(":/outdated.png"),
"to-be-outdated" : QIcon(":/to-be-outdated.png"),
}
self.outdatedTooltips = {
"update" : self.tr("Updates pending!"),
"outdated" : self.tr(
"The qube must be restarted for its filesystem to reflect"
" the template's recent committed changes."),
"to-be-outdated" : self.tr(
"The Template must be stopped before changes from its "
"current session can be picked up by this qube."),
}
def sizeHint(self, option, index):
hint = super().sizeHint(option, index)
option = QStyleOptionViewItem(option)
option.features |= option.HasDecoration
widget = option.widget
style = widget.style()
iconRect = style.subElementRect(style.SE_ItemViewItemDecoration,
option, widget)
width = iconRect.width() * 3 # Nº of possible icons
hint.setWidth(width)
return hint
def paint(self, qp, option, index):
# create a new QStyleOption (*never* use the one given in arguments)
option = QStyleOptionViewItem(option)
widget = option.widget
style = widget.style()
# paint the base item (borders, gradients, selection colors, etc)
style.drawControl(style.CE_ItemViewItem, option, qp, widget)
# "lie" about the decoration, to get a valid icon rectangle (even if we
# don't have any "real" icon set for the item)
option.features |= option.HasDecoration
iconRect = style.subElementRect(style.SE_ItemViewItemDecoration,
option, widget)
iconSize = iconRect.size()
margin = iconRect.left() - option.rect.left()
qp.save()
# ensure that we do not draw outside the item rectangle (and add some
# fancy margin on the right
qp.setClipRect(option.rect.adjusted(0, 0, -margin, 0))
# draw the main state icon, assuming all items have one
qp.drawPixmap(iconRect,
self.stateIcons[index.data()['power']].pixmap(iconSize))
left = delta = margin + iconRect.width()
if index.data()['outdated']:
qp.drawPixmap(iconRect.translated(left, 0),
self.outdatedIcons[index.data()['outdated']]\
.pixmap(iconSize))
left += delta
qp.restore()
def helpEvent(self, event, view, option, index):
if event.type() != QEvent.ToolTip:
return super().helpEvent(event, view,
option, index)
option = QStyleOptionViewItem(option)
widget = option.widget
style = widget.style()
option.features |= option.HasDecoration
iconRect = style.subElementRect(style.SE_ItemViewItemDecoration,
option, widget)
iconRect.setTop(option.rect.y())
iconRect.setHeight(option.rect.height())
# similar to what we do in the paint() method
if event.pos() in iconRect:
# (*) clear any existing tooltip; a single space is better , as
# sometimes it's not enough to use an empty string
if index != self.lastIndex:
QToolTip.showText(QPoint(), ' ')
QToolTip.showText(event.globalPos(),
index.data()['power'], view)
else:
margin = iconRect.left() - option.rect.left()
left = delta = margin + iconRect.width()
if index.data()['outdated']:
if event.pos() in iconRect.translated(left, 0):
# see above (*)
if index != self.lastIndex:
QToolTip.showText(QPoint(), ' ')
QToolTip.showText(event.globalPos(),
self.outdatedTooltips[index.data()['outdated']],
view)
# shift the left *only* if the role is True, otherwise we
# can assume that that icon doesn't exist at all
left += delta
self.lastIndex = index
return True
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-few-public-methods
class VmInfo():
def __init__(self, vm):
self.vm = vm
self.qid = vm.qid
self.name = self.vm.name
self.label = getattr(self.vm, 'label', None)
self.klass = getattr(self.vm, 'klass', None)
self.icon = getattr(vm, 'icon', 'appvm-black')
self.state = {'power': "", 'outdated': ""}
self.updateable = getattr(vm, 'updateable', False)
self.update(True)
def update_power_state(self):
try:
self.state['power'] = self.vm.get_power_state()
except exc.QubesDaemonAccessError:
self.state['power'] = ""
self.state['outdated'] = ""
try:
if manager_utils.is_running(self.vm, False):
if hasattr(self.vm, 'template') and \
manager_utils.is_running(self.vm.template, False):
self.state['outdated'] = "to-be-outdated"
else:
try:
if any(vol.is_outdated()
for vol in self.vm.volumes.values()):
self.state['outdated'] = "outdated"
except exc.QubesDaemonAccessError:
pass
if self.vm.klass in {'TemplateVM', 'StandaloneVM'} and \
manager_utils.get_feature(
self.vm, 'updates-available', False):
self.state['outdated'] = 'update'
except exc.QubesDaemonAccessError:
pass
def update(self, update_size_on_disk=False, event=None):
"""
Update VmInfo
:param update_size_on_disk: should disk utilization be updated?
:param event: name of the event that caused the update, to avoid
updating unnecessary properties; if event is none, update everything
:return: None
"""
self.update_power_state()
if not event or event.endswith(':label'):
self.label = getattr(self.vm, 'label', None)
self.icon = getattr(self.vm, 'icon', 'appvm-black')
if not event or event.endswith(':template'):
try:
self.template = self.vm.template.name
except AttributeError:
self.template = None
if not event or event.endswith(':netvm'):
self.netvm = getattr(self.vm, 'netvm', None)
if self.netvm:
self.netvm = str(self.netvm)
else:
self.netvm = "n/a"
try:
if hasattr(self.vm, 'netvm') \
and self.vm.property_is_default("netvm"):
self.netvm = "default (" + self.netvm + ")"
except exc.QubesDaemonAccessError:
pass
if not event or event.endswith(':internal'):
self.internal = manager_utils.get_boolean_feature(
self.vm, 'internal')
if not event or event.endswith(':ip'):
self.ip = getattr(self.vm, 'ip', "n/a")
if not event or event.endswith(':include_in_backups'):
self.inc_backup = getattr(self.vm, 'include_in_backups', None)
if not event or event.endswith(':backup_timestamp'):
self.last_backup = getattr(self.vm, 'backup_timestamp', None)
if self.last_backup:
self.last_backup = str(datetime.fromtimestamp(self.last_backup))
if not event or event.endswith(':default_dispvm'):
self.dvm = getattr(self.vm, 'default_dispvm', None)
try:
if self.vm.property_is_default("default_dispvm"):
self.dvm = "default (" + str(self.dvm) + ")"
elif self.dvm is not None:
self.dvm = str(self.dvm)
except exc.QubesDaemonAccessError:
if self.dvm is not None:
self.dvm = str(self.dvm)
if not event or event.endswith(':template_for_dispvms'):
self.dvm_template = getattr(self.vm, 'template_for_dispvms', None)
if self.vm.klass != 'AdminVM' and update_size_on_disk:
try:
self.disk_float = float(self.vm.get_disk_utilization())
self.disk = str(round(self.disk_float/(1024*1024), 2)) + " MiB"
except exc.QubesDaemonAccessError:
self.disk_float = None
self.disk = None
if self.vm.klass != 'AdminVM':
self.virt_mode = getattr(self.vm, 'virt_mode', None)
else:
self.virt_mode = None
self.disk = "n/a"
class QubesCache(QAbstractTableModel):
def __init__(self, qubes_app):
QAbstractTableModel.__init__(self)
self._qubes_app = qubes_app
self._info_list = []
self._info_by_id = {}
def add_vm(self, vm):
vm_info = VmInfo(vm)
self._info_list.append(vm_info)
self._info_by_id[vm.qid] = vm_info
def remove_vm(self, name):
vm_info = self.get_vm(name=name)
self._info_list.remove(vm_info)
del self._info_by_id[vm_info.qid]
def get_vm(self, row=None, qid=None, name=None):
if row is not None:
return self._info_list[row]
if qid is not None:
return self._info_by_id[qid]
return next(x for x in self._info_list if x.name == name)
def __len__(self):
return len(self._info_list)
def __iter__(self):
return iter(self._info_list)
class QubesTableModel(QAbstractTableModel):
def __init__(self, qubes_cache):
QAbstractTableModel.__init__(self)
self.qubes_cache = qubes_cache
self.template = {}
self.klass_pixmap = {}
self.label_pixmap = {}
self.columns_indices = [
"Type",
"Label",
"Name",
"State",
"Template",
"NetVM",
"Disk Usage",
"Internal",
"IP",
"Backup",
"Last backup",
"Default DispVM",
"Is DVM Template",
"Virt Mode"
]
# pylint: disable=invalid-name
def rowCount(self, _):
return len(self.qubes_cache)
# pylint: disable=invalid-name
def columnCount(self, _):
return len(self.columns_indices)
# pylint: disable=too-many-return-statements
def data(self, index, role):
if not index.isValid():
return None
col = index.column()
row = index.row()
col_name = self.columns_indices[col]
vm = self.qubes_cache.get_vm(row)
if role == Qt.DisplayRole:
if col in [0, 1]:
return None
if col_name == "Name":
return vm.name
if col_name == "State":
return vm.state
if col_name == "Template":
if vm.template is None:
return vm.klass
return vm.template
if col_name == "NetVM":
return vm.netvm
if col_name == "Disk Usage":
return vm.disk
if col_name == "Internal":
return "Yes" if vm.internal else ""
if col_name == "IP":
return vm.ip
if col_name == "Last backup":
return vm.last_backup
if col_name == "Default DispVM":
return vm.dvm
if col_name == "Is DVM Template":
return "Yes" if vm.dvm_template else ""
if col_name == "Virt Mode":
return vm.virt_mode
if role == Qt.DecorationRole:
if col_name == "Type":
try:
return self.klass_pixmap[vm.klass]
except KeyError:
pixmap = QPixmap()
icon_name = ":/"+vm.klass.lower()+".png"
icon_name = icon_name.replace("adminvm", "dom0")
icon_name = icon_name.replace("dispvm", "appvm")
pixmap.load(icon_name)
self.klass_pixmap[vm.klass] = pixmap.scaled(icon_size)
return self.klass_pixmap[vm.klass]
except exc.QubesDaemonAccessError:
return None
if col_name == "Label":
try:
return self.label_pixmap[vm.icon]
except (KeyError, AttributeError):
icon = QIcon.fromTheme(vm.icon)
self.label_pixmap[vm.icon] = icon.pixmap(icon_size)
return self.label_pixmap[vm.icon]
if role == Qt.CheckStateRole:
if col_name == "Backup":
return Qt.Checked if vm.inc_backup else Qt.Unchecked
if role == Qt.FontRole:
if col_name == "Template":
if vm.template is None:
font = QFont()
font.setItalic(True)
return font
if role == Qt.ForegroundRole:
if col_name == "Template":
if vm.template is None:
return QColor("gray")
# Used for get VM Object
if role == Qt.UserRole:
return vm
# Used for sorting
if role == Qt.UserRole + 1:
if vm.klass == 'AdminVM':
return ""
if col_name == "Type":
return vm.klass
if col_name == "Label":
return str(vm.label)
if col_name == "State":
return str(vm.state)
if col_name == "Disk Usage":
return vm.disk_float
return self.data(index, Qt.DisplayRole)
# pylint: disable=invalid-name
def headerData(self, col, orientation, role):
if col < 2:
return None
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self.columns_indices[col]
return None
def setData(self, index, value, role=Qt.EditRole):
if not index.isValid():
return False
if role == Qt.CheckStateRole:
col_name = self.columns_indices[index.column()]
if col_name == "Backup":
vm = self.qubes_cache.get_vm(index.row())
vm.vm.include_in_backups = (value == Qt.Checked)
vm.inc_backup = (value == Qt.Checked)
return True
return False
def flags(self, index):
if not index.isValid():
return Qt.NoItemFlags
def_flags = QAbstractTableModel.flags(self, index)
if self.columns_indices[index.column()] == "Backup":
return def_flags | Qt.ItemIsUserCheckable
return def_flags
vm_restart_check_timeout = 1000 # in msec
class VmShutdownMonitor(QObject):
def __init__(self, vm, check_time=vm_restart_check_timeout,
and_restart=False, caller=None):
QObject.__init__(self)
self.vm = vm
self.shutdown_timeout = vm.shutdown_timeout
self.check_time = check_time
self.and_restart = and_restart
self.shutdown_started = datetime.now()
self.caller = caller
def restart_vm_if_needed(self):
if self.and_restart and self.caller:
self.caller.start_vm(self.vm)
def check_again_later(self):
# noinspection PyTypeChecker,PyCallByClass
QTimer.singleShot(self.check_time, self.check_if_vm_has_shutdown)
def timeout_reached(self):
actual = datetime.now() - self.shutdown_started
allowed = timedelta(seconds=self.shutdown_timeout)
return actual > allowed
def check_if_vm_has_shutdown(self):
vm = self.vm
vm_is_running = manager_utils.is_running(vm, False)
try:
vm_start_time = datetime.fromtimestamp(float(vm.start_time))
except (AttributeError, TypeError, ValueError):
vm_start_time = None
if vm_is_running and vm_start_time \
and vm_start_time < self.shutdown_started:
if self.timeout_reached():
msgbox = QMessageBox(self.caller)
msgbox.setIcon(QMessageBox.Question)
msgbox.setWindowTitle(self.tr("Qube Shutdown"))
msgbox.setText(self.tr(
"The Qube <b>'{0}'</b> hasn't shutdown within the last "
"{1} seconds, do you want to kill it?<br>").format(
vm.name, self.shutdown_timeout))
kill_button = msgbox.addButton(
self.tr("Kill it!"), QMessageBox.YesRole)
wait_button = msgbox.addButton(
self.tr("Wait another {0} seconds...").format(
self.shutdown_timeout),
QMessageBox.NoRole)
ignore_button = msgbox.addButton(self.tr("Don't ask again"),
QMessageBox.RejectRole)
msgbox.setDefaultButton(wait_button)
msgbox.setEscapeButton(ignore_button)
msgbox.setWindowFlags(
msgbox.windowFlags() | Qt.CustomizeWindowHint)
msgbox.setWindowFlags(
msgbox.windowFlags() & ~Qt.WindowCloseButtonHint)
msgbox.exec_()
msgbox.deleteLater()
if msgbox.clickedButton() is kill_button:
try:
vm.kill()
except exc.QubesVMNotStartedError:
# the VM shut down while the user was thinking about
# shutting it down
pass
self.restart_vm_if_needed()
elif msgbox.clickedButton() is ignore_button:
return
else:
self.shutdown_started = datetime.now()
self.check_again_later()
else:
self.check_again_later()
else:
if vm_is_running:
# Due to unknown reasons, Xen sometimes reports that a domain
# is running even though its start-up timestamp is not valid.
# Make sure that "restart_vm_if_needed" is not called until
# the domain has been completely shut down according to Xen.
self.check_again_later()
return
self.restart_vm_if_needed()
# pylint: disable=too-few-public-methods
class StartVMThread(common_threads.QubesThread):
def run(self):
try:
self.vm.start()
except exc.QubesException as ex:
self.msg = ("Error starting Qube!", str(ex))
# pylint: disable=too-few-public-methods
class UpdateVMThread(common_threads.QubesThread):
def run(self):
try:
if self.vm.klass == 'AdminVM':
subprocess.check_call(
["/usr/bin/qubes-dom0-update", "--clean", "--gui"])
else:
if not manager_utils.is_running(self.vm, False):
try:
self.vm.start()
except exc.QubesDaemonAccessError:
# permission denied, let us hope for the best
pass
# apply DSA-4371
with open('/usr/libexec/qubes-manager/dsa-4371-update', 'rb') \
as dsa4371update:
stdout, stderr = self.vm.run_service_for_stdio(
"qubes.VMShell",
user="root",
input=dsa4371update.read())
if stdout == b'changed=yes\n':
subprocess.call(
['notify-send', '-i', 'dialog-information',
self.tr('Debian DSA-4371 fix installed in {}').format(
self.vm.name)])
elif stdout == b'changed=no\n':
pass
else:
raise exc.QubesException(
self.tr("Failed to apply DSA-4371 fix: {}").format(
stderr.decode('ascii')))
self.vm.run_service("qubes.InstallUpdatesGUI",
user="root", wait=False)
except (ChildProcessError, exc.QubesException) as ex:
self.msg = (self.tr("Error on qube update!"), str(ex))
# pylint: disable=too-few-public-methods
class RunCommandThread(common_threads.QubesThread):
def __init__(self, vm, command_to_run):
super().__init__(vm)
self.command_to_run = command_to_run
def run(self):
try:
self.vm.run(self.command_to_run)
except (ChildProcessError, exc.QubesException) as ex:
self.msg = (self.tr("Error while running command!"), str(ex))
class QubesProxyModel(QSortFilterProxyModel):
def __init__(self, window):
super().__init__()
self.window = window
def lessThan(self, left, right):
if left.data(self.sortRole()) != right.data(self.sortRole()):
return super().lessThan(left, right)
left_vm = left.data(Qt.UserRole)
right_vm = right.data(Qt.UserRole)
return left_vm.name.lower() < right_vm.name.lower()
# pylint: disable=too-many-return-statements
def filterAcceptsRow(self, sourceRow, sourceParent):
if self.window.show_all.isChecked():
return super().filterAcceptsRow(sourceRow, sourceParent)
index = self.sourceModel().index(sourceRow, 0, sourceParent)
vm = self.sourceModel().data(index, Qt.UserRole)
if self.window.show_running.isChecked() and \
vm.state['power'] != 'Halted':
return super().filterAcceptsRow(sourceRow, sourceParent)
if self.window.show_halted.isChecked() and \
vm.state['power'] == 'Halted':
return super().filterAcceptsRow(sourceRow, sourceParent)
if self.window.show_network.isChecked() and \
getattr(vm.vm, 'provides_network', False):
return super().filterAcceptsRow(sourceRow, sourceParent)
if self.window.show_templates.isChecked() and vm.klass == 'TemplateVM':
return super().filterAcceptsRow(sourceRow, sourceParent)
if self.window.show_standalone.isChecked() \
and vm.klass == 'StandaloneVM':
return super().filterAcceptsRow(sourceRow, sourceParent)
return False
class VmManagerWindow(ui_qubemanager.Ui_VmManagerWindow, QMainWindow):
# suppress saving settings while initializing widgets
settings_loaded = False
def __init__(self, qt_app, qubes_app, dispatcher, _parent=None):
super().__init__()
self.setupUi(self)
self.manager_settings = QSettings(self)
self.qubes_app = qubes_app
self.qt_app = qt_app
self.searchbox = SearchBox()
self.searchbox.setValidator(QRegExpValidator(
QRegExp("[a-zA-Z0-9_-]*", Qt.CaseInsensitive), None))
self.searchbox.textChanged.connect(self.do_search)
self.searchContainer.insertWidget(1, self.searchbox)
self.settings_windows = {}
self.frame_width = 0
self.frame_height = 0
self.init_template_menu()
self.init_network_menu()
self.__init_context_menu()
self.tools_context_menu = QMenu(self)
self.tools_context_menu.addAction(self.action_toolbar)
self.tools_context_menu.addAction(self.action_menubar)
self.menubar.customContextMenuRequested.connect(
lambda pos: self.open_tools_context_menu(self.menubar, pos))
self.toolbar.customContextMenuRequested.connect(
lambda pos: self.open_tools_context_menu(self.toolbar, pos))
self.action_menubar.toggled.connect(self.showhide_menubar)
self.action_toolbar.toggled.connect(self.showhide_toolbar)
self.action_show_logs.triggered.connect(self.show_log)
self.action_compact_view.toggled.connect(self.set_compactview)
self.table.resizeColumnsToContents()
self.update_size_on_disk = False
self.shutdown_monitor = {}
self.qubes_cache = QubesCache(qubes_app)
self.fill_cache()
self.qubes_model = QubesTableModel(self.qubes_cache)
self.proxy = QubesProxyModel(self)
self.proxy.setSourceModel(self.qubes_model)
self.proxy.setSortRole(Qt.UserRole + 1)
self.proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
self.proxy.setFilterKeyColumn(2)
self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
self.proxy.layoutChanged.connect(self.save_sorting)
self.proxy.layoutChanged.connect(self.update_template_menu)
self.proxy.layoutChanged.connect(self.update_network_menu)
self.show_running.stateChanged.connect(self.invalidate)
self.show_halted.stateChanged.connect(self.invalidate)
self.show_network.stateChanged.connect(self.invalidate)
self.show_templates.stateChanged.connect(self.invalidate)
self.show_standalone.stateChanged.connect(self.invalidate)
self.show_all.stateChanged.connect(self.invalidate)
self.table.setModel(self.proxy)
self.table.setItemDelegateForColumn(3, StateIconDelegate())
self.table.resizeColumnsToContents()
selection_model = self.table.selectionModel()
selection_model.selectionChanged.connect(self.table_selection_changed)
self.table.setContextMenuPolicy(Qt.CustomContextMenu)
self.table.customContextMenuRequested.connect(self.open_context_menu)
# Create view menu
for col_no in range(len(self.qubes_model.columns_indices)):
column = self.qubes_model.columns_indices[col_no]
action = self.menu_view.addAction(column)
action.setData(column)
action.setCheckable(True)
action.toggled.connect(partial(self.showhide_column, col_no))
self.menu_view.addSeparator()
self.menu_view.addAction(self.action_toolbar)
self.menu_view.addAction(self.action_menubar)
self.menu_view.addSeparator()
self.menu_view.addAction(self.action_compact_view)
try:
self.load_manager_settings()
except Exception as ex: # pylint: disable=broad-except
QMessageBox.warning(
self,
self.tr("Manager settings unreadable"),
self.tr("Qube Manager settings cannot be parsed. Previously "
"saved display settings may not be restored "
"correctly.\nError: {}".format(str(ex))))
self.settings_loaded = True
# Connect events
self.dispatcher = dispatcher
dispatcher.add_handler('domain-pre-start',
self.on_domain_status_changed)
dispatcher.add_handler('domain-start', self.on_domain_status_changed)
dispatcher.add_handler('domain-start-failed',
self.on_domain_status_changed)
dispatcher.add_handler('domain-stopped', self.on_domain_status_changed)
dispatcher.add_handler('domain-pre-shutdown',
self.on_domain_status_changed)
dispatcher.add_handler('domain-shutdown', self.on_domain_status_changed)
dispatcher.add_handler('domain-paused', self.on_domain_status_changed)
dispatcher.add_handler('domain-unpaused', self.on_domain_status_changed)
dispatcher.add_handler('domain-add', self.on_domain_added)
dispatcher.add_handler('domain-delete', self.on_domain_removed)
dispatcher.add_handler('property-set:*',
self.on_domain_changed)
dispatcher.add_handler('property-del:*',
self.on_domain_changed)
dispatcher.add_handler('property-load',
self.on_domain_changed)
dispatcher.add_handler('domain-feature-set:internal',
self.on_domain_changed)
dispatcher.add_handler('domain-feature-delete:internal',
self.on_domain_changed)
dispatcher.add_handler('domain-feature-set:updates-available',
self.on_domain_updates_available)
dispatcher.add_handler('domain-feature-delete:updates-available',
self.on_domain_updates_available)
# It needs to store threads until they finish
self.threads_list = []
self.progress = None
self.check_updates()
def change_template(self, template):
selected_vms = self.get_selected_vms()
reply = QMessageBox.question(
self, self.tr("Template Change Confirmation"),
self.tr("Do you want to change '{0}'<br>"
"to Template <b>'{1}'</b>?").format(
', '.join(vm.name for vm in selected_vms), template),
QMessageBox.Yes | QMessageBox.Cancel)
if reply == QMessageBox.Yes:
errors = []
for info in selected_vms:
try:
info.vm.template = template
except exc.QubesValueError as ex:
errors.append((info.name, str(ex)))
for error in errors:
QMessageBox.warning(self, self.tr("{0} template change failed!")
.format(error[0]), error[1])
def change_network(self, netvm_name):
selected_vms = self.get_selected_vms()
reply = QMessageBox.question(
self, self.tr("Network Change Confirmation"),
self.tr("Do you want to change '{0}'<br>"
"to Network <b>'{1}'</b>?").format(
', '.join(vm.name for vm in selected_vms), netvm_name),
QMessageBox.Yes | QMessageBox.Cancel)
if reply != QMessageBox.Yes:
return
if netvm_name not in [None, 'default']:
check_power = any(info.state['power'] == 'Running' for info
in self.get_selected_vms())
netvm = self.qubes_cache.get_vm(name=netvm_name)
if check_power and netvm.state['power'] != 'Running':
reply = QMessageBox.question(
self, self.tr("Qube Start Confirmation"),
self.tr("<br>Can not change netvm to a halted Qube.<br>"
"Do you want to start the Qube <b>'{0}'</b>?").format(
netvm_name),
QMessageBox.Yes | QMessageBox.Cancel)
if reply == QMessageBox.Yes:
self.start_vm(netvm.vm, True)
else:
return
errors = []
for info in self.get_selected_vms():
try:
if netvm_name == 'default':
delattr(info.vm, 'netvm')
else:
info.vm.netvm = netvm_name
except exc.QubesValueError as ex:
errors.append((info.name, str(ex)))
for error in errors:
QMessageBox.warning(self, self.tr("{0} network change failed!")
.format(error[0]), error[1])
def __init_context_menu(self):
self.context_menu = QMenu(self)
self.context_menu.addAction(self.action_settings)
self.context_menu.addAction(self.template_menu.menuAction())
self.context_menu.addAction(self.network_menu.menuAction())
self.context_menu.addAction(self.action_editfwrules)
self.context_menu.addAction(self.action_appmenus)
self.context_menu.addAction(self.action_set_keyboard_layout)
self.context_menu.addSeparator()
self.context_menu.addAction(self.action_updatevm)
self.context_menu.addAction(self.action_run_command_in_vm)
self.context_menu.addAction(self.action_open_console)
self.context_menu.addAction(self.action_resumevm)
self.context_menu.addAction(self.action_startvm_tools_install)
self.context_menu.addAction(self.action_pausevm)
self.context_menu.addAction(self.action_shutdownvm)
self.context_menu.addAction(self.action_restartvm)
self.context_menu.addAction(self.action_killvm)
self.context_menu.addSeparator()
self.context_menu.addAction(self.action_clonevm)
self.context_menu.addAction(self.action_removevm)
self.context_menu.addSeparator()
self.context_menu.addAction(self.action_show_logs)
def save_showing(self):
self.manager_settings.setValue('show/running',
self.show_running.isChecked())
self.manager_settings.setValue('show/halted',
self.show_halted.isChecked())
self.manager_settings.setValue('show/network',
self.show_network.isChecked())
self.manager_settings.setValue('show/templates',
self.show_templates.isChecked())
self.manager_settings.setValue('show/standalone',
self.show_standalone.isChecked())
self.manager_settings.setValue('show/all', self.show_all.isChecked())
def save_sorting(self):
self.manager_settings.setValue('view/sort_column',
self.proxy.sortColumn())
self.manager_settings.setValue('view/sort_order',
self.proxy.sortOrder())
def invalidate(self):
self.proxy.invalidate()
self.table.resizeColumnsToContents()
def fill_cache(self):
progress = QProgressDialog(
self.tr(
"Loading Qube Manager..."), "", 0,
len(self.qubes_app.domains.keys()))
progress.setWindowTitle(self.tr("Qube Manager"))
progress.setMinimumDuration(1000)
progress.setWindowModality(Qt.WindowModal)
progress.setCancelButton(None)
row_no = 0
for vm in self.qubes_app.domains:
progress.setValue(row_no)
self.qubes_cache.add_vm(vm)
row_no += 1
progress.setValue(row_no)
def init_template_menu(self):
self.template_menu.clear()
for vm in self.qubes_app.domains:
if vm.klass == 'TemplateVM':
action = self.template_menu.addAction(vm.name)
action.setData(vm.name)
action.triggered.connect(partial(self.change_template, vm.name))
def _get_default_netvm(self):
for vm in self.qubes_app.domains:
if vm.klass == 'AppVM':
return vm.property_get_default('netvm')
def init_network_menu(self):
default = self._get_default_netvm()
self.network_menu.clear()
action = self.network_menu.addAction("None")
action.triggered.connect(partial(self.change_network, None))
action = self.network_menu.addAction("default ({0})".format(default))
action.triggered.connect(partial(self.change_network, 'default'))
for vm in self.qubes_app.domains:
if vm.qid != 0 and vm.provides_network:
action = self.network_menu.addAction(vm.name)
action.setData(vm.name)
action.triggered.connect(partial(self.change_network, vm.name))
def setup_application(self):
self.qt_app.setApplicationName(self.tr("Qube Manager"))
self.qt_app.setWindowIcon(QIcon.fromTheme("qubes-manager"))
def keyPressEvent(self, event): # pylint: disable=invalid-name
if event.key() == Qt.Key_Escape:
self.searchbox.clear()
super().keyPressEvent(event)
def clear_threads(self):
for thread in self.threads_list:
if thread.isFinished():
if self.progress:
self.progress.hide()
self.progress = None