-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathview_tab.py
2519 lines (2092 loc) · 112 KB
/
view_tab.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
import os
import json
import time
import base64
import pty
import select
import subprocess
import termios
import tty
import re
import threading
import socket
import psutil
import yaml
from datetime import datetime, timezone
import csv
from functools import lru_cache
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QFileDialog, QProgressDialog,
QComboBox, QTableView, QTextEdit, QPushButton, QSplitter, QLabel, QGridLayout,
QLineEdit, QStyleFactory, QStatusBar, QTabWidget, QHeaderView, QCheckBox, QDialog, QInputDialog,
QGroupBox, QScrollArea, QMessageBox, QDialogButtonBox, QFormLayout, QSpinBox, QTableWidget,
QTableWidgetItem, QSizePolicy, QRadioButton, QButtonGroup, QAbstractItemView, QFrame
)
from PyQt5.QtGui import (
QStandardItemModel, QFont, QColor, QTextCharFormat, QStandardItem, QTextCursor, QPalette,
QTextDocument, QTextBlockFormat, QKeyEvent, QTextTableFormat, QTextFrameFormat, QTextLength
)
from PyQt5.QtCore import Qt, QSortFilterProxyModel, QTimer, QRegExp, QThread, pyqtSignal, QMetaObject, QUrl, QProcess, pyqtSlot, Q_ARG, QMetaType
from kubernetes import client, config
from kubernetes.stream import stream
from resource_updaters import (
update_pods, update_pvcs, update_statefulsets, update_deployments, update_pvs,
update_secrets, update_configmaps, update_jobs, update_cronjobs, update_nodes,
LogStreamerThread, parse_k8s_cpu, parse_k8s_memory
)
from utils import setup_info_search
import numpy as np
import sip
from ssh_dialog import SSHDialog
from pod_metrics_worker import PodMetricsWorker
from helper_view_tab.create_resource_dialog import CreateResourceDialog
from helper_view_tab.edit_resource_dialog import EditResourceDialog
from helper_view_tab.ssh_connection import SSHAuthDialog, SSHConnectionThread
from helper_view_tab.terminal_widget import TerminalWidget
from helper_view_tab.utils import clean_resource_dict, decode_base64_in_yaml, save_port_forwarding, load_port_forwarding
def kill_port_forward_processes(pattern):
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
if 'kubectl' in proc.info['name'] and 'port-forward' in proc.info['cmdline'] and any(pattern in arg for arg in proc.info['cmdline']):
proc.terminate()
proc.wait(timeout=5)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
pass
class ViewTab(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
self.selected_namespaces = []
self.port_forwarding_file = os.path.join(os.path.expanduser("~"), ".kube_debugger_port_forwarding.json")
self.port_forwarding_dict = load_port_forwarding(self.port_forwarding_file)
self.edit_dialog_open = False
self.init_ui()
self.check_active_port_forwardings()
self.separate_terminal_window = None
self.load_ssh_key_from_kubeconfig()
self.ssh_output_buffer = ""
self.ssh_timer = QTimer()
self.ssh_timer.timeout.connect(self.process_ssh_output)
self.ssh_timer.start(50)
self.selection_timer = QTimer()
self.selection_timer.setSingleShot(True)
self.selection_timer.timeout.connect(self.delayed_update_resource_info)
# Load namespaces only once
self.load_namespaces()
self.update_resources()
self.refresh_events()
# Connect signals after initialization
self.namespace_combo1.currentIndexChanged.connect(self.on_namespace_changed)
self.namespace_combo2.currentIndexChanged.connect(self.on_namespace_changed)
def on_namespace_changed(self):
self.update_resources()
def create_labeled_combo(self, label_text, combo_items=None):
layout = QHBoxLayout()
layout.setSpacing(50)
layout.setContentsMargins(2, 2, 2, 2)
label = QLabel(label_text)
label.setFixedWidth(200) # Adjust this value as needed
label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
combo = QComboBox()
if combo_items:
combo.addItems(combo_items)
combo.setFixedWidth(200) # Adjust this value as needed
layout.addWidget(label)
layout.addWidget(combo)
layout.addStretch(1)
return layout, combo
def init_ui(self):
main_layout = QVBoxLayout(self)
self.main_layout = main_layout
self.main_layout.setSpacing(2)
self.main_layout.setContentsMargins(2, 2, 2, 2)
# Create splitter for left and right panels
self.splitter = QSplitter(Qt.Horizontal)
main_layout.addWidget(self.splitter)
# Left panel
left_widget = QWidget()
left_layout = QVBoxLayout(left_widget)
left_layout.setSpacing(10)
# First line: Namespace and Resource Type
first_line_layout = QHBoxLayout()
first_line_layout.addWidget(QLabel("Namespace 1:"))
self.namespace_combo1 = QComboBox()
first_line_layout.addWidget(self.namespace_combo1)
first_line_layout.addWidget(QLabel("Namespace 2:"))
self.namespace_combo2 = QComboBox()
first_line_layout.addWidget(self.namespace_combo2)
# Add "More Namespaces" dropdown
self.more_namespaces_button = QPushButton("More namespaces")
self.more_namespaces_button.clicked.connect(self.show_namespace_dialog)
first_line_layout.addWidget(self.more_namespaces_button)
first_line_layout.addStretch(1)
left_layout.addLayout(first_line_layout)
# Resource type tabs
self.resource_tabs = QTabWidget()
self.resource_tabs.setDocumentMode(True)
self.resource_tabs.setTabPosition(QTabWidget.North)
self.resource_tabs.addTab(QWidget(), "Pods")
self.resource_tabs.addTab(QWidget(), "Deployments")
self.resource_tabs.addTab(QWidget(), "StatefulSets")
self.resource_tabs.addTab(QWidget(), "Jobs")
self.resource_tabs.addTab(QWidget(), "CronJobs")
self.resource_tabs.addTab(QWidget(), "PVC")
self.resource_tabs.addTab(QWidget(), "PV")
self.resource_tabs.addTab(QWidget(), "Secrets")
self.resource_tabs.addTab(QWidget(), "ConfigMaps")
self.resource_tabs.addTab(QWidget(), "Services")
self.resource_tabs.addTab(QWidget(), "Nodes")
left_layout.addWidget(self.resource_tabs)
# Adjust size policy of the tab widget
self.resource_tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
# Second line: Search, Refresh, and Download
second_line_layout = QHBoxLayout()
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Filter resources...")
second_line_layout.addWidget(self.search_input)
self.refresh_button = QPushButton("Refresh")
second_line_layout.addWidget(self.refresh_button)
self.download_resources_button = QPushButton("Download")
second_line_layout.addWidget(self.download_resources_button)
left_layout.addLayout(second_line_layout)
# Resource Table
resource_label = QLabel("Resource Table")
left_layout.addWidget(resource_label)
self.resource_table = QTableView()
self.table_model = QStandardItemModel()
self.proxy_model = QSortFilterProxyModel()
self.proxy_model.setSourceModel(self.table_model)
self.resource_table.setModel(self.proxy_model)
self.resource_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
self.resource_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.resource_table.setSelectionMode(QAbstractItemView.SingleSelection)
self.resource_table.horizontalHeader().setStretchLastSection(True)
self.resource_table.verticalHeader().setVisible(False)
# Add these lines
self.resource_table.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel)
self.resource_table.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel)
self.resource_table.setShowGrid(False)
left_layout.addWidget(self.resource_table)
# Events and Terminal section
events_terminal_widget = QWidget()
self.events_terminal_layout = QVBoxLayout(events_terminal_widget)
# Create a tab widget for events and terminal
self.events_terminal_tabs = QTabWidget()
self.events_terminal_layout.addWidget(self.events_terminal_tabs)
left_layout.addWidget(events_terminal_widget)
# Events tab
events_tab = QWidget()
events_tab_layout = QVBoxLayout(events_tab)
# Events controls
events_controls_layout = QHBoxLayout()
events_label = QLabel("Latest Events")
events_controls_layout.addWidget(events_label)
self.events_filter = QLineEdit()
self.events_filter.setPlaceholderText("Filter events...")
events_controls_layout.addWidget(self.events_filter)
refresh_events_button = QPushButton("Refresh")
events_controls_layout.addWidget(refresh_events_button)
refresh_events_button.clicked.connect(self.refresh_events)
download_events_button = QPushButton("Download")
events_controls_layout.addWidget(download_events_button)
download_events_button.clicked.connect(self.download_events_table)
events_tab_layout.addLayout(events_controls_layout)
self.events_table = QTableWidget()
self.events_table.setColumnCount(5)
self.events_table.setHorizontalHeaderLabels(["Namespace", "Event Time", "Reason", "Object", "Message"])
self.events_table.setSelectionBehavior(QAbstractItemView.SelectRows)
self.events_table.setSelectionMode(QAbstractItemView.SingleSelection)
self.events_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
self.events_table.horizontalHeader().setStretchLastSection(True)
self.events_table.setSortingEnabled(True)
events_tab_layout.addWidget(self.events_table)
self.events_terminal_tabs.addTab(events_tab, "Events")
# Terminal tab
self.terminal_tab = QWidget()
terminal_layout = QVBoxLayout(self.terminal_tab)
self.terminal_widget = TerminalWidget(self)
terminal_layout.addWidget(self.terminal_widget)
expand_button = QPushButton("Expand Terminal")
expand_button.clicked.connect(self.expand_terminal)
terminal_layout.addWidget(expand_button)
self.events_terminal_tabs.addTab(self.terminal_tab, "Terminal")
self.splitter.addWidget(left_widget)
# Right panel
right_widget = QWidget()
right_layout = QVBoxLayout(right_widget)
right_layout.setSpacing(10)
# Resource Info Header
self.current_resource_label = QLabel()
right_layout.addWidget(self.current_resource_label)
# Container selection
container_layout = QHBoxLayout()
self.container_label = QLabel("Container:")
self.container_combo = QComboBox()
container_layout.addWidget(self.container_label)
container_layout.addWidget(self.container_combo)
right_layout.addLayout(container_layout)
# Action buttons and checkboxes layout
action_info_layout = QHBoxLayout()
action_info_layout.setSpacing(10) # Add spacing between widgets
# Create a widget to hold all buttons
button_widget = QWidget()
button_layout = QHBoxLayout(button_widget)
button_layout.setSpacing(5) # Spacing between buttons
button_layout.setContentsMargins(0, 0, 0, 0) # Remove margins
info_download_button = QPushButton("Download")
info_download_button.clicked.connect(self.download_info)
info_download_button.setFixedSize(120, 30) # Set fixed size
button_layout.addWidget(info_download_button)
self.edit_yaml_button = QPushButton("Edit")
self.edit_yaml_button.setFixedSize(120, 30) # Set fixed size
button_layout.addWidget(self.edit_yaml_button)
# Create action buttons
self.action_buttons = {}
button_data = [
('delete', "Delete", self.delete_current_resource),
('stream_logs', "Stream", self.stream_logs),
('port_forward', "Port Forward", self.port_forward_current_service),
('ssh', "SSH", lambda: self.ssh_to_node(self.current_resource_name)),
('exec', "Exec", self.toggle_exec_panel)
]
for key, text, action in button_data:
button = QPushButton(text)
button.setFixedSize(120, 30) # Set fixed size
button.clicked.connect(action)
if key == 'exec':
button.setCheckable(True)
self.action_buttons[key] = button
button_layout.addWidget(button)
button.hide()
action_info_layout.addWidget(button_widget)
# Add stretch to push checkboxes to the right
action_info_layout.addStretch(1)
self.decode_checkbox = QCheckBox("Decode Base64")
self.decode_checkbox.hide()
action_info_layout.addWidget(self.decode_checkbox)
self.show_full_yaml_checkbox = QCheckBox("Show Full YAML")
action_info_layout.addWidget(self.show_full_yaml_checkbox)
self.show_full_yaml_checkbox.stateChanged.connect(self.update_info_display)
right_layout.addLayout(action_info_layout)
# New section with QTabWidget
self.info_tabs = QTabWidget()
self.describe_tab = QWidget()
self.logs_tab = QWidget()
self.events_tab = QWidget()
self.volumes_tab = QWidget()
# Create layouts for each tab
describe_layout = QVBoxLayout(self.describe_tab)
logs_layout = QVBoxLayout(self.logs_tab)
events_layout = QVBoxLayout(self.events_tab)
volumes_layout = QVBoxLayout(self.volumes_tab)
# Add separate QTextEdit to each tab
self.describe_text = QTextEdit()
self.describe_text.setReadOnly(True)
describe_layout.addWidget(self.describe_text)
self.logs_text = QTextEdit()
self.logs_text.setReadOnly(True)
logs_layout.addWidget(self.logs_text)
self.events_text = QTextEdit()
self.events_text.setReadOnly(True)
events_layout.addWidget(self.events_text)
self.volumes_text = QTextEdit()
self.volumes_text.setReadOnly(True)
volumes_layout.addWidget(self.volumes_text)
self.info_tabs.addTab(self.describe_tab, "Describe")
self.info_tabs.addTab(self.logs_tab, "Logs")
self.info_tabs.addTab(self.events_tab, "Events")
self.info_tabs.addTab(self.volumes_tab, "Volumes")
self.update_info_type_combo()
# Add info_tabs to the layout
right_layout.addWidget(self.info_tabs)
# Exec section
self.exec_label = QLabel("Execute Command")
right_layout.addWidget(self.exec_label)
exec_layout = QHBoxLayout()
self.exec_input = QLineEdit()
self.exec_input.setPlaceholderText("Enter command")
exec_layout.addWidget(self.exec_input)
self.exec_button = QPushButton("Execute")
exec_layout.addWidget(self.exec_button)
self.exec_download_button = QPushButton("Download")
exec_layout.addWidget(self.exec_download_button)
right_layout.addLayout(exec_layout)
self.exec_output = QTextEdit()
self.exec_output.setReadOnly(True)
right_layout.addWidget(self.exec_output)
self.splitter.addWidget(right_widget)
# Set initial splitter sizes
self.splitter.setSizes([int(self.width() * 0.7), int(self.width() * 0.3)])
# Connect signals
self.refresh_button.clicked.connect(self.manual_refresh)
self.resource_tabs.currentChanged.connect(self.on_resource_type_changed)
self.search_input.textChanged.connect(self.filter_resources)
self.resource_table.selectionModel().selectionChanged.connect(self.on_selection_changed)
self.container_combo.currentIndexChanged.connect(self.update_info_display)
self.info_tabs.currentChanged.connect(self.update_info_display)
self.decode_checkbox.stateChanged.connect(self.update_info_display)
self.edit_yaml_button.clicked.connect(self.edit_resource_yaml)
self.events_filter.textChanged.connect(self.filter_events)
self.download_resources_button.clicked.connect(self.download_resource_table)
self.exec_button.clicked.connect(self.execute_command)
self.exec_download_button.clicked.connect(self.download_exec_output)
# Hide container selection by default
self.container_label.hide()
self.container_combo.hide()
# Hide exec panel by default
self.exec_label.hide()
self.exec_input.hide()
self.exec_button.hide()
self.exec_download_button.hide()
self.exec_output.hide()
# Set up info search
setup_info_search(self)
# Load namespaces and initial resources
self.load_namespaces()
# Start the terminal
self.start_terminal()
self.terminal_widget.command_entered.connect(self.send_command)
def on_selection_changed(self, selected, deselected):
if selected.indexes():
# Cancel any pending update
self.selection_timer.stop()
# Schedule a new update
self.selection_timer.start(50) # 50ms delay
def show_namespace_dialog(self):
namespaces = [ns.metadata.name for ns in self.v1.list_namespace().items]
dialog = QDialog(self)
dialog.setWindowTitle("Select Namespaces")
dialog.setMinimumWidth(300) # Set a minimum width for the dialog
main_layout = QVBoxLayout(dialog)
# Create a scroll area for the namespaces
scroll_area = QScrollArea()
scroll_area.setWidgetResizable(True)
scroll_content = QWidget()
scroll_layout = QVBoxLayout(scroll_content)
namespace_checkboxes = []
all_selected_namespaces = set(self.selected_namespaces)
all_selected_namespaces.add(self.namespace_combo1.currentText())
all_selected_namespaces.add(self.namespace_combo2.currentText())
for ns in namespaces:
checkbox = QCheckBox(ns)
if ns in all_selected_namespaces:
checkbox.setChecked(True)
namespace_checkboxes.append(checkbox)
scroll_layout.addWidget(checkbox)
scroll_area.setWidget(scroll_content)
# Set a maximum height for the scroll area
scroll_area.setMaximumHeight(300) # Adjust this value as needed
main_layout.addWidget(scroll_area)
# Add a separator line
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
main_layout.addWidget(line)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(lambda: self.set_selected_namespaces(namespace_checkboxes, dialog))
button_box.rejected.connect(dialog.reject)
main_layout.addWidget(button_box)
dialog.exec_()
def set_selected_namespaces(self, namespace_checkboxes, dialog):
self.selected_namespaces = [checkbox.text() for checkbox in namespace_checkboxes if checkbox.isChecked()]
print(f"Selected namespaces: {self.selected_namespaces}") # Log message
dialog.accept()
self.update_resources()
def get_selected_namespaces(self):
return [self.namespace_combo1.currentText(), self.namespace_combo2.currentText()] + self.selected_namespaces
def toggle_exec_panel(self):
if self.action_buttons['exec'].isChecked():
self.show_exec_elements()
else:
self.hide_exec_elements()
def display_resource_info(self, resource):
resource_dict = resource.to_dict()
self.clean_resource_dict(resource_dict)
if self.show_full_yaml_checkbox.isChecked():
formatted_output = self.format_resource_info(resource_dict)
else:
formatted_output = self.format_resource_info({'spec': resource_dict.get('spec', {})})
self.describe_text.setPlainText(formatted_output)
def disable_cluster_dependent_ui(self):
self.namespace_combo1.setEnabled(False)
self.namespace_combo2.setEnabled(False)
self.refresh_button.setEnabled(False)
self.download_resources_button.setEnabled(False)
self.resource_table.setEnabled(False)
def enable_cluster_dependent_ui(self):
self.namespace_combo1.setEnabled(True)
self.namespace_combo2.setEnabled(True)
self.refresh_button.setEnabled(True)
self.download_resources_button.setEnabled(True)
self.resource_table.setEnabled(True)
def update_info_type_combo(self):
resource_type = self.get_current_resource_type()
if resource_type == "Pods":
self.info_tabs.setTabEnabled(self.info_tabs.indexOf(self.describe_tab), True)
self.info_tabs.setTabEnabled(self.info_tabs.indexOf(self.logs_tab), True)
self.info_tabs.setTabEnabled(self.info_tabs.indexOf(self.events_tab), True)
self.info_tabs.setTabEnabled(self.info_tabs.indexOf(self.volumes_tab), True)
else:
self.info_tabs.setTabEnabled(self.info_tabs.indexOf(self.describe_tab), True)
self.info_tabs.setTabEnabled(self.info_tabs.indexOf(self.logs_tab), False)
self.info_tabs.setTabEnabled(self.info_tabs.indexOf(self.events_tab), False)
self.info_tabs.setTabEnabled(self.info_tabs.indexOf(self.volumes_tab), False)
# Select the first available tab if the current one is disabled
if not self.info_tabs.isTabEnabled(self.info_tabs.currentIndex()):
self.info_tabs.setCurrentIndex(self.info_tabs.indexOf(self.describe_tab))
def on_resource_type_changed(self):
try:
# Disconnect previous connections if they exist
try:
self.resource_table.selectionModel().selectionChanged.disconnect()
except TypeError:
pass # No connections to disconnect
resource_type = self.get_current_resource_type()
# Show/hide action buttons based on resource type
self.action_buttons['delete'].setVisible(resource_type != "Nodes")
self.action_buttons['stream_logs'].setVisible(resource_type == "Pods")
self.action_buttons['port_forward'].setVisible(resource_type == "Services")
self.action_buttons['ssh'].setVisible(resource_type == "Nodes")
self.update_resources()
# Reconnect the signal
self.resource_table.selectionModel().selectionChanged.connect(self.update_resource_info)
except Exception as e:
print(f"Error in on_resource_type_changed: {str(e)}")
# You might want to show an error message to the user here
self.update_info_type_combo() # Ensure tabs are updated based on resource type
self.update_info_display()
def update_action_buttons(self):
resource_type = self.get_current_resource_type()
for button in self.action_buttons.values():
button.hide()
if resource_type != "Nodes":
self.action_buttons['delete'].show()
if resource_type == "Pods":
self.action_buttons['stream_logs'].show()
self.action_buttons['exec'].show()
if resource_type == "Services":
self.action_buttons['port_forward'].show()
if resource_type == "Nodes":
self.action_buttons['ssh'].show()
def download_resource_table(self):
file_name, _ = QFileDialog.getSaveFileName(self, "Save Resource Table", "", "CSV Files (*.csv)")
if file_name:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
# Write headers
headers = [self.table_model.headerData(i, Qt.Horizontal) for i in range(self.table_model.columnCount())]
writer.writerow(headers)
# Write data
for row in range(self.table_model.rowCount()):
row_data = [self.table_model.data(self.table_model.index(row, col)) for col in range(self.table_model.columnCount())]
writer.writerow(row_data)
QMessageBox.information(self, "Download Complete", "Resource table has been saved successfully.")
def download_events_table(self):
self.download_events_button.setEnabled(False)
self.download_events_button.setText("Downloading...")
QApplication.processEvents() # Update the UI immediately
progress_dialog = QProgressDialog("Downloading events table...", "Cancel", 0, 0, self)
progress_dialog.setWindowModality(Qt.WindowModal)
progress_dialog.setRange(0, 0) # Indeterminate progress
progress_dialog.show()
try:
file_name, _ = QFileDialog.getSaveFileName(self, "Save Events Table", "", "CSV Files (*.csv)")
if file_name:
with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
# Write headers
headers = [self.events_table.horizontalHeaderItem(i).text() for i in range(self.events_table.columnCount())]
writer.writerow(headers)
# Write data
for row in range(self.events_table.rowCount()):
row_data = [self.events_table.item(row, col).text() if self.events_table.item(row, col) else '' for col in range(self.events_table.columnCount())]
writer.writerow(row_data)
QMessageBox.information(self, "Download Complete", "Events table has been saved successfully.")
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to download events table: {str(e)}")
finally:
self.download_events_button.setEnabled(True)
self.download_events_button.setText("Download")
progress_dialog.close()
def edit_resource_yaml(self):
if not self.current_resource_name:
QMessageBox.warning(self, "No Resource Selected", "Please select a resource to edit.")
return
resource_type = self.get_current_resource_type()
dialog = EditResourceDialog(resource_type, self.current_resource_name, self.current_namespace, self, self)
if dialog.exec_() == QDialog.Accepted:
edited_yaml = dialog.get_edited_yaml()
self.apply_edited_resource(edited_yaml, resource_type)
def apply_edited_resource(self, edited_yaml, resource_type):
try:
edited_spec = yaml.safe_load(edited_yaml)['spec']
name = self.current_resource_name
namespace = self.current_namespace
# Show loading indicator
progress_dialog = QProgressDialog("Applying changes...", "Cancel", 0, 0, self)
progress_dialog.setWindowModality(Qt.WindowModal)
progress_dialog.show()
try:
if resource_type == "Pods":
current_pod = self.v1.read_namespaced_pod(name, namespace)
if 'containers' in edited_spec:
for i, container in enumerate(edited_spec['containers']):
if i < len(current_pod.spec.containers):
if 'image' in container:
current_pod.spec.containers[i].image = container['image']
if 'resources' in container:
current_pod.spec.containers[i].resources = client.V1ResourceRequirements(**container['resources'])
self.v1.replace_namespaced_pod(name, namespace, current_pod)
elif resource_type == "Deployments":
current_deployment = self.apps_v1.read_namespaced_deployment(name, namespace)
if 'replicas' in edited_spec:
current_deployment.spec.replicas = edited_spec['replicas']
if 'template' in edited_spec and 'spec' in edited_spec['template']:
template_spec = edited_spec['template']['spec']
if 'containers' in template_spec:
for i, container in enumerate(template_spec['containers']):
if i < len(current_deployment.spec.template.spec.containers):
if 'image' in container:
current_deployment.spec.template.spec.containers[i].image = container['image']
if 'resources' in container:
current_deployment.spec.template.spec.containers[i].resources = client.V1ResourceRequirements(**container['resources'])
self.apps_v1.replace_namespaced_deployment(name, namespace, current_deployment)
elif resource_type == "StatefulSets":
current_statefulset = self.apps_v1.read_namespaced_stateful_set(name, namespace)
if 'replicas' in edited_spec:
current_statefulset.spec.replicas = edited_spec['replicas']
if 'template' in edited_spec and 'spec' in edited_spec['template']:
template_spec = edited_spec['template']['spec']
if 'containers' in template_spec:
for i, container in enumerate(template_spec['containers']):
if i < len(current_statefulset.spec.template.spec.containers):
if 'image' in container:
current_statefulset.spec.template.spec.containers[i].image = container['image']
if 'resources' in container:
current_statefulset.spec.template.spec.containers[i].resources = client.V1ResourceRequirements(**container['resources'])
self.apps_v1.replace_namespaced_stateful_set(name, namespace, current_statefulset)
elif resource_type == "Jobs":
current_job = self.batch_v1.read_namespaced_job(name, namespace)
if 'template' in edited_spec and 'spec' in edited_spec['template']:
template_spec = edited_spec['template']['spec']
if 'containers' in template_spec:
for i, container in enumerate(template_spec['containers']):
if i < len(current_job.spec.template.spec.containers):
if 'image' in container:
current_job.spec.template.spec.containers[i].image = container['image']
if 'resources' in container:
current_job.spec.template.spec.containers[i].resources = client.V1ResourceRequirements(**container['resources'])
self.batch_v1.replace_namespaced_job(name, namespace, current_job)
elif resource_type == "CronJobs":
current_cronjob = self.batch_v1.read_namespaced_cron_job(name, namespace)
if 'schedule' in edited_spec:
current_cronjob.spec.schedule = edited_spec['schedule']
if 'jobTemplate' in edited_spec and 'spec' in edited_spec['jobTemplate']:
job_template_spec = edited_spec['jobTemplate']['spec']
if 'template' in job_template_spec and 'spec' in job_template_spec['template']:
template_spec = job_template_spec['template']['spec']
if 'containers' in template_spec:
for i, container in enumerate(template_spec['containers']):
if i < len(current_cronjob.spec.job_template.spec.template.spec.containers):
if 'image' in container:
current_cronjob.spec.job_template.spec.template.spec.containers[i].image = container['image']
if 'resources' in container:
current_cronjob.spec.job_template.spec.template.spec.containers[i].resources = client.V1ResourceRequirements(**container['resources'])
self.batch_v1.replace_namespaced_cron_job(name, namespace, current_cronjob)
elif resource_type == "PVC":
current_pvc = self.v1.read_namespaced_persistent_volume_claim(name, namespace)
if 'resources' in edited_spec:
current_pvc.spec.resources = client.V1ResourceRequirements(**edited_spec['resources'])
self.v1.replace_namespaced_persistent_volume_claim(name, namespace, current_pvc)
elif resource_type == "PV":
current_pv = self.v1.read_persistent_volume(name)
if 'capacity' in edited_spec:
current_pv.spec.capacity = edited_spec['capacity']
self.v1.replace_persistent_volume(name, current_pv)
elif resource_type == "Secrets":
current_secret = self.v1.read_namespaced_secret(name, namespace)
if 'data' in edited_spec:
current_secret.data = {k: base64.b64encode(v.encode()).decode() for k, v in edited_spec['data'].items()}
self.v1.replace_namespaced_secret(name, namespace, current_secret)
elif resource_type == "ConfigMaps":
current_configmap = self.v1.read_namespaced_config_map(name, namespace)
if 'data' in edited_spec:
current_configmap.data = edited_spec['data']
self.v1.replace_namespaced_config_map(name, namespace, current_configmap)
elif resource_type == "Services":
current_service = self.v1.read_namespaced_service(name, namespace)
if 'ports' in edited_spec:
current_service.spec.ports = [client.V1ServicePort(**port) for port in edited_spec['ports']]
if 'selector' in edited_spec:
current_service.spec.selector = edited_spec['selector']
self.v1.replace_namespaced_service(name, namespace, current_service)
elif resource_type == "Nodes":
current_node = self.v1.read_node(name)
if 'metadata' in edited_spec and 'labels' in edited_spec['metadata']:
current_node.metadata.labels = edited_spec['metadata']['labels']
self.v1.replace_node(name, current_node)
else:
raise ValueError(f"Editing not supported for resource type: {resource_type}")
QMessageBox.information(self, "Success", f"{resource_type} '{name}' updated successfully")
self.update_info_display() # Refresh the resource info display
except client.exceptions.ApiException as e:
error_message = json.loads(e.body)['message'] if e.body else str(e)
QMessageBox.critical(self, "Error", f"Failed to apply changes: {error_message}")
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to apply changes: {str(e)}")
finally:
progress_dialog.close()
except yaml.YAMLError as e:
QMessageBox.critical(self, "Error", f"Failed to parse edited YAML: {str(e)}")
except KeyError as e:
QMessageBox.critical(self, "Error", f"Invalid structure in edited YAML: {str(e)}")
def create_new_resource(self):
namespaces = [ns.metadata.name for ns in self.v1.list_namespace().items]
dialog = CreateResourceDialog(namespaces, self)
if dialog.exec_() == QDialog.Accepted:
namespace = dialog.get_namespace()
resource_yaml = dialog.get_resource_yaml()
# Show loading indicator
progress_dialog = QProgressDialog("Creating resource...", "Cancel", 0, 0, self)
progress_dialog.setWindowModality(Qt.WindowModal)
progress_dialog.show()
try:
self.apply_new_resource(namespace, resource_yaml)
except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to create resource: {str(e)}")
finally:
progress_dialog.close()
@lru_cache(maxsize=100)
def get_resource_info(self, resource_type, resource_name, namespace):
try:
if resource_type == "Pods":
return self.v1.read_namespaced_pod(resource_name, namespace)
elif resource_type == "Deployments":
return self.apps_v1.read_namespaced_deployment(resource_name, namespace)
elif resource_type == "StatefulSets":
return self.apps_v1.read_namespaced_stateful_set(resource_name, namespace)
elif resource_type == "Jobs":
return self.batch_v1.read_namespaced_job(resource_name, namespace)
elif resource_type == "CronJobs":
return self.batch_v1.read_namespaced_cron_job(resource_name, namespace)
elif resource_type == "PVC":
return self.v1.read_namespaced_persistent_volume_claim(resource_name, namespace)
elif resource_type == "Secrets":
return self.v1.read_namespaced_secret(resource_name, namespace)
elif resource_type == "ConfigMaps":
return self.v1.read_namespaced_config_map(resource_name, namespace)
elif resource_type == "Services":
return self.v1.read_namespaced_service(resource_name, namespace)
elif resource_type == "PV":
return self.v1.read_persistent_volume(resource_name)
elif resource_type == "Nodes":
return self.v1.read_node(resource_name)
else:
raise ValueError(f"Unsupported resource type: {resource_type}")
except client.exceptions.ApiException as e:
print(f"API Exception when fetching {resource_type} {resource_name}: {e}")
return None
def update_describe_tab(self):
resource_type = self.get_current_resource_type()
resource = self.get_resource_info(resource_type, self.current_resource_name, self.current_namespace)
self.display_resource_info(resource)
def update_logs_tab(self):
container = self.container_combo.currentText() if self.container_combo.isVisible() else None
try:
logs = self.v1.read_namespaced_pod_log(
self.current_resource_name,
self.current_namespace,
container=container
)
self.logs_text.setPlainText(logs)
except client.rest.ApiException as e:
self.logs_text.setPlainText(f"Error fetching logs: {str(e)}")
def apply_new_resource(self, namespace, resource_yaml):
try:
resource_dict = yaml.safe_load(resource_yaml)
kind = resource_dict["kind"]
name = resource_dict["metadata"]["name"]
confirm_msg = f"Are you sure you want to apply the {kind} '{name}' in namespace '{namespace}'?"
reply = QMessageBox.question(self, 'Confirm Apply', confirm_msg,
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.No:
return
api_client = client.ApiClient()
utils = client.ApiClient().sanitize_for_serialization(resource_dict)
if kind == "Pod":
api_instance = client.CoreV1Api(api_client)
api_instance.create_namespaced_pod(namespace, utils)
elif kind == "Deployment":
api_instance = client.AppsV1Api(api_client)
api_instance.create_namespaced_deployment(namespace, utils)
elif kind == "Service":
api_instance = client.CoreV1Api(api_client)
api_instance.create_namespaced_service(namespace, utils)
elif kind == "PersistentVolumeClaim" or kind == "PVC":
api_instance = client.CoreV1Api(api_client)
api_instance.create_namespaced_persistent_volume_claim(namespace, utils)
elif kind == "StatefulSet":
api_instance = client.AppsV1Api(api_client)
api_instance.create_namespaced_stateful_set(namespace, utils)
elif kind == "PersistentVolume" or kind == "PV":
api_instance = client.CoreV1Api(api_client)
api_instance.create_persistent_volume(utils)
elif kind == "Secret":
api_instance = client.CoreV1Api(api_client)
api_instance.create_namespaced_secret(namespace, utils)
elif kind == "ConfigMap":
api_instance = client.CoreV1Api(api_client)
api_instance.create_namespaced_config_map(namespace, utils)
elif kind == "Job":
api_instance = client.BatchV1Api(api_client)
api_instance.create_namespaced_job(namespace, utils)
elif kind == "CronJob":
api_instance = client.BatchV1Api(api_client)
api_instance.create_namespaced_cron_job(namespace, utils)
else:
raise ValueError(f"Unsupported resource type: {kind}")
QMessageBox.information(self, "Success", f"{kind} applied successfully in namespace {namespace}")
self.update_resources()
except Exception as e:
raise Exception(f"Failed to apply new resource: {str(e)}")
def check_active_port_forwardings(self):
self.verify_port_forwarding()
for key, (local_port, pid) in self.port_forwarding_dict.items():
namespace, service_name = key.split('/')
QMetaObject.invokeMethod(self, "update_port_forwarding_status",
Qt.QueuedConnection,
Q_ARG(str, namespace),
Q_ARG(str, service_name),
Q_ARG(bool, True))
def stop_port_forwarding(self, namespace, service_name):
key = f"{namespace}/{service_name}"
if key in self.port_forwarding_dict:
local_port, pid = self.port_forwarding_dict[key]
try:
process = psutil.Process(pid)
process.terminate()
try:
process.wait(timeout=5)
except psutil.TimeoutExpired:
process.kill()
except psutil.NoSuchProcess:
print(f"Process for {key} not found")
# Kill any remaining kubectl port-forward process for this service
kill_port_forward_processes(f"kubectl port-forward.*{namespace}/{service_name}")
del self.port_forwarding_dict[key]
self.save_port_forwarding()
self.update_resources() # Refresh the table to update the button status
QMessageBox.information(self, "Port Forwarding", f"Port forwarding stopped for service {service_name}")
else:
QMessageBox.warning(self, "Port Forwarding", f"No active port forwarding found for service {service_name}")
@pyqtSlot(str, str, bool)
def update_port_forwarding_status(self, namespace, service_name, is_active):
key = f"{namespace}/{service_name}"
if is_active:
# Port forwarding started
if key not in self.port_forwarding_dict:
print(f"Error: Key {key} not found in port_forwarding_dict")
return
port = self.port_forwarding_dict[key]
QMessageBox.information(self, "Port Forwarding",
f"Port forwarding active for {service_name}\n"
f"Local address: localhost:{port}")
else:
# Port forwarding stopped
if key in self.port_forwarding_dict:
del self.port_forwarding_dict[key]
QMessageBox.information(self, "Port Forwarding",
f"Port forwarding stopped for {service_name}")
self.update_resources()
@pyqtSlot(str)
def show_error_message(self, message):
QMessageBox.critical(self, "Error", message)
def port_forward_service(self, service_name, namespace):
try:
service = self.v1.read_namespaced_service(service_name, namespace)
available_ports = [f"{port.port}:{port.target_port}" for port in service.spec.ports]
port_dialog = QDialog(self)
port_dialog.setWindowTitle("Choose Port")
port_layout = QVBoxLayout(port_dialog)
port_combo = QComboBox()
port_combo.addItems(available_ports)
port_layout.addWidget(QLabel("Select port to forward:"))
port_layout.addWidget(port_combo)
local_port_input = QLineEdit()
local_port_input.setPlaceholderText("Enter local port")
port_layout.addWidget(QLabel("Local port:"))
port_layout.addWidget(local_port_input)
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
button_box.accepted.connect(port_dialog.accept)
button_box.rejected.connect(port_dialog.reject)
port_layout.addWidget(button_box)