-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathki.py
More file actions
executable file
·1563 lines (1423 loc) · 71.6 KB
/
Copy pathki.py
File metadata and controls
executable file
·1563 lines (1423 loc) · 71.6 KB
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
#*************************************************
# Description : Kubectl Pro
# Version : 7.0
#*************************************************
from collections import deque, Counter
from ast import literal_eval
import os,re,sys,time,readline,subprocess,hashlib
#-----------------VAR-----------------------------
home = os.environ["HOME"]
history = home + "/.history"
ki_cool = history + "/.cool"
ki_cache = history + "/.cache"
ki_ns_dict = history + "/.ns_dict"
ki_pod_dict = history + "/.pod_dict"
ki_kube_dict = history + "/.kube_dict"
ki_latest_ns_dict = history + "/.latest_ns_dict"
ki_current_ns_dict = history + "/.current_ns_dict"
ki_last = history + "/.last"
ki_line = history + "/.line"
ki_lock = history + "/.lock"
ki_unlock = history + "/.unlock"
default_config = home + "/.kube/config"
session_config = None
KI_AI_URL = os.getenv("KI_AI_URL", "https://api.xairouter.com/v1/chat/completions")
KI_AI_KEY = os.getenv("KI_AI_KEY", "sk-XvsJhNdiXcDYA3e5hzD1AJP5ploMAaFuMTUxp3bHRfCiZRNt")
KI_AI_MODEL = os.getenv("KI_AI_MODEL", "MiniMax-M2.1")
KI_AUTO_SWITCH = os.getenv("KI_AUTO_SWITCH", "true").lower() not in ("false", "0", "no")
KI_AUTO_CACHE = os.getenv("KI_AUTO_CACHE", "true").lower() not in ("false", "0", "no")
KUBECTL_OPTIONS = "--insecure-skip-tls-verify"
CACHE_DURATION = 8 * 60 * 60
NS_CACHE_DURATION = 300
LOCK_TIMEOUT = 3600
CACHE_EXPIRY_SECONDS = 86400
GOLDEN_RATIO = 0.618
BUFFER_SIZE = 8192
SCORE_PENALTY = 8192
HISTORY_SCORE_HIGH = 72
HISTORY_SCORE_MID = 24
HISTORY_SCORE_LOW = -24
HISTORY_SCORE_DEFAULT = 8
RESOURCE_TYPE_SHORT = {
'd':'Deployment','s':'Service','i':'Ingress','f':'StatefulSet',
'a':'DaemonSet','p':'Pod','g':'Gateway','h':'HTTPRoute',
'A':'all','V':'VirtualService','D':'DestinationRule','E':'EnvoyFilter'
}
RESOURCE_TYPE_MAPPING = {
's':"Service",'i':"Ingress"
}
RESOURCE_TYPE_FULL = {
'd':['Deployment'," -o wide"],'s':['Service'," -o wide"],
'i':['Ingress'," -o wide"],'c':['ConfigMap'," -o wide"],
't':['Secret'," -o wide"],'n':['Node'," -o wide"],
'p':['PersistentVolumeClaim'," -o wide"],'v':['PersistentVolume'," -o wide"],
'f':['StatefulSet'," -o wide"],'j':['CronJob'," -o wide"],
'b':['Job'," -o wide"],'P':['Pod'," -o wide"],
'e':['Event',''],'r':['ReplicaSet',''],'a':['DaemonSet',''],
'q':['ResourceQuota',''],'V':['VirtualService',""],
'g':['Gateway',''],'h':['HTTPRoute',''],'A':['all',''],
'E':['EnvoyFilter',''],'D':['DestinationRule','']
}
#-----------------FUN-----------------------------
def switch_kubeconfig(target_config):
"""切换 kubeconfig 配置"""
if os.path.lexists(session_config):
os.unlink(session_config)
os.symlink(target_config, session_config)
if os.path.exists(default_config):
os.unlink(default_config)
os.symlink(target_config, default_config)
def get_session_id():
session_id = None
if 'XDG_SESSION_ID' in os.environ:
session_id = os.environ['XDG_SESSION_ID']
elif 'SSH_TTY' in os.environ:
session_id = os.environ['SSH_TTY'].split('/')[-1]
elif 'SSH_AUTH_SOCK' in os.environ:
session_id = os.environ['SSH_AUTH_SOCK'].split('.')[-1]
elif 'TERM_SESSION_ID' in os.environ:
session_id = os.environ['TERM_SESSION_ID'][:10]
else:
session_id = "default"
session_id = re.sub(r'[^\w\-]', '_', str(session_id))
return session_id
def get_session_config():
session_id = get_session_id()
return home + f"/.kube/config-sess-{session_id}"
def init_session_config():
global session_config
session_config = get_session_config()
if not os.path.lexists(session_config):
if os.path.exists(default_config) and os.path.islink(default_config):
target = os.path.realpath(default_config)
if os.path.exists(target):
os.symlink(target, session_config)
else:
find_first_valid_config()
elif os.path.exists(default_config):
config_0_path = home+"/.kube/config-0"
if not os.path.exists(config_0_path):
os.rename(default_config, config_0_path)
else:
if os.path.lexists(default_config):
os.unlink(default_config)
if os.path.lexists(default_config):
os.unlink(default_config)
os.symlink(config_0_path, default_config)
if os.path.lexists(session_config):
os.unlink(session_config)
os.symlink(config_0_path, session_config)
else:
find_first_valid_config()
def find_first_valid_config():
cmd = '''find $HOME/.kube -maxdepth 2 -type f -name 'kubeconfig*' -a ! -name 'kubeconfig-*-NULL' -a ! -name 'config-sess-*' 2>/dev/null|egrep '.*' || ( find $HOME/.kube -maxdepth 1 -type f 2>/dev/null|egrep '.*' &>/dev/null && grep -l "current-context" `find $HOME/.kube -maxdepth 1 -type f|grep -v 'config-sess-'` )'''
result_set = { e.split('\n')[0] for e in get_data(cmd) }
if result_set:
first_config = list(result_set)[0]
if os.path.lexists(default_config):
os.unlink(default_config)
os.symlink(first_config, default_config)
if os.path.lexists(session_config):
os.unlink(session_config)
os.symlink(first_config, session_config)
def cmp_file(f1, f2):
if os.path.getsize(f1) != os.path.getsize(f2):
return False
bufsize = BUFFER_SIZE
with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
while True:
b1 = fp1.read(bufsize)
b2 = fp2.read(bufsize)
if b1 != b2:
return False
if not b1 and not b2:
return True
def confirm_action(caution):
try:
confirm = input(caution+", Confirm execution of high-risk operation? (yes/no): ")
return confirm.lower() in ("yes","y")
except:
return False
def cmd_obj(ns, obj, res, args, iip="x"):
name = res
if obj in ("Node"):
if args[0] in ('c','u'):
action = "cordon" if args[0] == 'c' else "uncordon"
cmd = f"kubectl {KUBECTL_OPTIONS} "+action+" "+res
elif args[0] in ('d','e'):
action = "describe" if args[0] == 'd' else "edit"
cmd = f"kubectl {KUBECTL_OPTIONS} "+action+" "+obj.lower()+" "+res
elif args[0] == 'o':
action = "get"
action2 = " -o yaml > "+res+"."+obj.lower()+".yml"
cmd = f"kubectl {KUBECTL_OPTIONS} "+action+" "+obj.lower()+" "+res+action2
else:
action = "ssh"
node_ip = get_data(f"kubectl {KUBECTL_OPTIONS} get node " + res + " -o jsonpath='{.status.addresses[?(@.type==\"InternalIP\")].address}'")[0]
if find_ip(node_ip):
cmd = action +" root@"+node_ip
else:
cmd = action +" root@"+iip
elif obj in ("Event"):
action = "get"
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" "+action+" "+obj+" --sort-by=.metadata.creationTimestamp"
elif obj in ("Deployment","DaemonSet","Service","StatefulSet","Ingress","ConfigMap","Secret","PersistentVolume","PersistentVolumeClaim","CronJob","Job","VirtualService","Gateway","HTTPRoute","DestinationRule","EnvoyFilter", "all"):
action2 = ""
actual_obj = obj
actual_res = res
if obj == "all" and "/" in res:
parts = res.split("/", 1)
if len(parts) == 2:
actual_obj = parts[0].capitalize()
actual_res = parts[1]
if args in ("cle","delete"):
if confirm_action("This command will delete the "+actual_obj):
action = "delete"
else:
print("Operation canceled.")
return
elif args[0] == "e":
action = "edit"
elif args[0] == "d":
action = "describe"
elif args[0] == 'o':
action = "get"
action2 = " -o yaml > "+actual_res+"."+actual_obj.lower()+".yml"
else:
action = "get"
actual_obj = obj
actual_res = res
if obj == "all" and args[0] in ('e', 'd', 'o'):
cmd = f"kubectl {KUBECTL_OPTIONS} -n {ns} {action} {actual_obj.lower()} {actual_res}{action2}"
else:
cmd = f"kubectl {KUBECTL_OPTIONS} -n {ns} {action} {actual_obj.lower()} {actual_res}{action2}" if actual_obj not in ("PersistentVolume") else f"kubectl {KUBECTL_OPTIONS} {action} {actual_obj.lower()} {actual_res}{action2}"
elif obj in ("ResourceQuota"):
action2 = ""
if args[0] == "e":
action = "edit"
elif args[0] == "d":
action = "describe"
elif args[0] == 'o':
action = "get"
action2 = " -o yaml > "+ns+"."+obj.lower()+".yml"
elif args in ("cle","delete"):
if confirm_action("This command will delete the "+obj):
action = "delete"
else:
print("Operation canceled.")
return
else:
action = "get"
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" "+action+" "+obj.lower()+" "+res+action2
else:
l = get_obj(ns,res)
obj = l[0]
name = l[1]
d = RESOURCE_TYPE_SHORT
if args == "p":
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" exec -it "+res+" -- sh"
elif args == "del":
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" delete pod "+res+" --wait=false"
elif args == "delf":
action = "delete"
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" delete pod "+res+" --grace-period=0 --force"
elif args in ("cle","delete"):
if confirm_action("This command will delete the deployment associated with the pod"):
action = "delete"
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" "+action+" "+obj.lower()+" "+name
else:
print("Operation canceled.")
return
elif args in ("destroy","destory"):
if confirm_action("Delete associated Deployment, Service, and Ingress resources for the Pod"):
action = "delete"
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" "+action+" "+obj.lower()+",service,ingress "+name
else:
print("Operation canceled.")
return
elif args[0] in ('l', 'c', 'g'):
search_term = args[1:].strip()
try:
result_list = get_data(f"kubectl {KUBECTL_OPTIONS} -n "+ns+" get pod "+res+" -o jsonpath='{.spec.containers[:].name}'")[0].split()
except:
sys.exit()
container = "--all-containers --max-log-requests=28"
if search_term:
if search_term.isdigit():
if 0 < int(search_term) < 10000:
os.environ['KI_LINE'] = search_term
with open(ki_line,'w') as f:
f.write(search_term)
if search_term.isdigit() and len(search_term) < 12:
cmd = f"kubectl {KUBECTL_OPTIONS} -n {ns} logs -f {res} {container} --tail {search_term}"
else:
if args[0] == 'l':
cmd = f"kubectl {KUBECTL_OPTIONS} -n {ns} logs -f --tail 1024 {res} {container} | grep -a --color=auto '{search_term}'"
else:
grep_option = "" if args[0] == 'g' else "-C 10"
cmd = f"kubectl {KUBECTL_OPTIONS} -n {ns} logs -f {res} {container} | grep -a --color=auto {grep_option} '{search_term}'"
else:
if 'KI_LINE' in os.environ:
line = os.environ['KI_LINE']
elif os.path.exists(ki_line):
with open(ki_line,'r') as f:
line_file = str(f.read())
os.environ['KI_LINE'] = line_file if line_file.isdigit() and int(line_file) < 4096 else str(200)
line = os.environ['KI_LINE']
else:
line = str(200)
cmd = f"kubectl {KUBECTL_OPTIONS} -n {ns} logs -f {res} {container} --tail {line}"
elif args[0] in ('v'):
regular = args[1:]
try:
result_list = get_data(f"kubectl {KUBECTL_OPTIONS} -n "+ns+" get pod "+res+" -o jsonpath='{.spec.containers[:].name}'")[0].split()
except:
sys.exit()
container = name if name in result_list else "--all-containers"
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" logs -f "+res+" "+container+" --previous --tail "+ ( regular if regular and regular.isdigit() and len(regular) < 12 else "4096" )
elif args[0] in ('r'):
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" rollout restart "+obj.lower()+" "+name
elif args[0] in ('u'):
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" rollout undo "+obj.lower()+"/"+name
elif args[0] in ('o'):
action = "get"
if len(args) > 1:
obj = d.get(args[1],'Pod')
if obj == 'Pod': name = res
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" "+action+" "+obj.lower()+" "+name+" -o yaml > "+name+"."+obj.lower()+".yml"
elif args[0] in ('d','e'):
action = "describe" if args[0] == 'd' else "edit"
if len(args) > 1:
obj = d.get(args[1],'Pod')
if obj == 'Pod': name = res
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" "+action+" "+obj.lower()+" "+name
elif args[0] in ('s'):
if confirm_action("This command will scale the "+obj):
regular = args.split('s')[-1]
action = "scale"
replicas = regular if regular.isdigit() and -1 < int(regular) < 30 else str(1)
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" "+action+" --replicas="+replicas+" "+obj.lower()+"/"+name
else:
print("Operation canceled.")
return
elif args[0] in ('n'):
action = "ssh"
try:
hostIP = get_data(f"kubectl {KUBECTL_OPTIONS} -n "+ns+" get pod "+res+" -o jsonpath='{.status.hostIP}'")[0]
except:
sys.exit()
cmd = action +" root@"+hostIP
else:
cmd = "kubectl {KUBECTL_OPTIONS} -n "+ns+" exec -it "+res+" -- sh"
return cmd,obj,name
def find_ip(res: str):
ip_regex = r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
ips = re.findall(ip_regex, res)
return ips[0] if ips else ""
def find_optimal(namespace_list: list, namespace: str):
namespace_list.sort()
has_namespace = [namespace in row for row in namespace_list]
index_scores = [row.index(namespace) * GOLDEN_RATIO if has_namespace[i] else SCORE_PENALTY for i, row in enumerate(namespace_list)]
contain_scores = [len(row.replace(namespace, '')) * GOLDEN_RATIO for row in namespace_list]
result_scores = [(index_scores[i] + container) * (1 if has_namespace[i] else 1 + GOLDEN_RATIO) for i, container in enumerate(contain_scores)]
if result_scores:
return namespace_list[result_scores.index(min(result_scores))] if len(set(index_scores)) != 1 else ( namespace_list[has_namespace.index(True)] if True in has_namespace else None )
else:
return None
def find_config():
global header_config
os.path.exists(history) or os.mkdir(history)
init_session_config()
current_config = session_config
cmd = '''find $HOME/.kube -maxdepth 2 -type f -name 'kubeconfig*' -a ! -name 'kubeconfig-*-NULL' -a ! -name 'config-sess-*' 2>/dev/null|egrep '.*' || ( find $HOME/.kube -maxdepth 1 -type f 2>/dev/null|egrep '.*' &>/dev/null && grep -l "current-context" `find $HOME/.kube -maxdepth 1 -type f|grep -v 'config-sess-'` )'''
result_set = { e.split('\n')[0] for e in get_data(cmd) }
result_num = len(result_set)
result_lines = list(result_set)
kubeconfig = None
if result_num == 1:
target_config = result_lines[0]
if os.path.exists(current_config):
if not os.path.islink(current_config):
os.unlink(current_config)
os.symlink(target_config, current_config)
elif os.path.realpath(current_config) != target_config:
os.unlink(current_config)
os.symlink(target_config, current_config)
else:
os.symlink(target_config, current_config)
if os.path.exists(default_config):
os.unlink(default_config)
os.symlink(target_config, default_config)
kubeconfig = target_config.split("/")[-1]
header_config = os.path.realpath(current_config)
elif result_num > 1:
dc = {}
if os.path.exists(ki_kube_dict) and os.path.getsize(ki_kube_dict) > 5:
with open(ki_kube_dict,'r') as f:
try:
dc = literal_eval(f.read())
for config in list(dc.keys()):
if not os.path.exists(config):
del dc[config]
except:
os.unlink(ki_kube_dict)
if os.path.exists(ki_last) and os.path.getsize(ki_last) > 0:
with open(ki_last,'r') as f:
last_config = f.read()
if not os.path.exists(last_config):
last_config = result_lines[0]
else:
last_config = result_lines[0]
result_dict = sorted(dc.items(),key = lambda dc:(dc[1], dc[0]),reverse=True)
sort_list = deque([ i[0] for i in result_dict ])
header_config = sort_list[0] if sort_list else os.path.realpath(current_config) if os.path.exists(current_config) else result_lines[0]
last_config in sort_list and sort_list.remove(last_config)
sort_list.appendleft(last_config)
result_lines = list(sort_list) + list(result_set - set(sort_list))
if os.path.exists(current_config):
if not os.path.islink(current_config):
os.unlink(current_config)
os.symlink(result_lines[0], current_config)
kubeconfig = result_lines[0].split("/")[-1]
else:
for e in result_lines:
if cmp_file(e, current_config):
kubeconfig = e.strip().split("/")[-1]
if not kubeconfig:
os.unlink(current_config)
os.symlink(result_lines[0], current_config)
kubeconfig = result_lines[0].split("/")[-1]
else:
os.symlink(result_lines[0], current_config)
kubeconfig = result_lines[0].split("/")[-1]
else:
if os.path.exists(current_config):
header_config = os.path.realpath(current_config)
else:
header_config = default_config
return [kubeconfig,result_lines,result_num]
def compress_list(l: list):
if len(l) > 3:
num = 15
i = 0
while i + 2 < len(l):
if l[i+1] - l[i] > num and l[i] > 0 and l[i+2] > 1:
l[i] -= 1
l[i+1] = min(l[i] + num, l[i+1])
l[i+2] -= 2
else:
i += 1
if l[-1] - l[-2] < num + 1:
return l
else:
l[0] = 1
l[-1] = l[-2] + 1
return compress_list(l)
else:
return l
def find_history(config,num=3):
if config != header_config:
dc = {}
if os.path.exists(ki_kube_dict) and os.path.getsize(ki_kube_dict) > 5:
with open(ki_kube_dict,'r') as f:
dc = literal_eval(f.read())
dc[config] = dc[config] + num if config in dc else 1
dc.pop(default_config,None)
dc.pop(session_config,None)
for config in list(dc.keys()):
if not os.path.exists(config) or 'config-sess-' in config:
del dc[config]
else:
dc[config] = 1
result_dict = sorted(dc.items(),key = lambda dc:dc[1])
for i,j in zip(result_dict,compress_list([ i[1] for i in result_dict ])):
dc[i[0]] = j
with open(ki_kube_dict,'w') as f: f.write(str(dc))
def get_config(config_lines: list, ns: str):
history_lines = []
dc = {}
if os.path.exists(ki_kube_dict):
with open(ki_kube_dict, 'r') as f:
dc = literal_eval(f.read())
dc.pop(os.path.realpath(default_config), None)
dc.pop(os.path.realpath(session_config), None) if session_config else None
history_lines = [k[0] for k in sorted(dc.items(), key=lambda d: d[1], reverse=True)]
current_config = session_config if session_config and os.path.exists(session_config) else default_config
real_current = os.path.realpath(current_config) if os.path.exists(current_config) else None
if real_current and real_current in config_lines:
config_lines.remove(real_current)
matching_configs = [config for config in config_lines if ns in config]
if not matching_configs:
return current_config
def score_config(config):
base_score = dc.get(config, 0)
match_score = len(set(config.lower()) & set(ns.lower())) / len(set(ns.lower()))
history_score = len(history_lines) - history_lines.index(config) if config in history_lines else 0
total_score = base_score * 0.5 + match_score * 0.3 + history_score * 0.2
return total_score
scored_configs = [(config, score_config(config)) for config in matching_configs]
scored_configs.sort(key=lambda x: x[1], reverse=True)
return scored_configs[0][0]
def find_ns(config_struct: list):
ns = None
kubeconfig = None
switch = False
ns_dict = ki_ns_dict
result_num = config_struct[-1]
kn = re.split("[./]",sys.argv[2])
ns_pattern = kn[-1] if len(kn) > 1 and len(kn[-1].strip()) > 0 else kn[0]
current_config = session_config if session_config and os.path.exists(session_config) else default_config
if os.path.exists(ki_current_ns_dict) and int(time.time()-os.stat(ki_current_ns_dict).st_mtime) < NS_CACHE_DURATION:
with open(ki_current_ns_dict) as f:
try:
d = literal_eval(f.read())
real_config = os.path.realpath(current_config)
if real_config in d:
ns_list = d[real_config]
if find_optimal(ns_list,ns_pattern):
ns_dict = ki_current_ns_dict
config_struct[1] = [real_config]
except:
os.path.exists(ki_cache) and os.unlink(ki_cache)
config = get_config(config_struct[1], kn[0]) or current_config if len(kn) > 1 else current_config
if len(config_struct[1]) > 1:
real_config = os.path.realpath(config)
config_struct[1] = deque(config_struct[1])
real_config in config_struct[1] and config_struct[1].remove(real_config)
config_struct[1].appendleft(real_config)
for n,config in enumerate(config_struct[1]):
if os.path.exists(ns_dict):
with open(ns_dict,'r') as f:
try:
d = literal_eval(f.read())
ns_list = d.get(config, [])
except:
os.path.exists(ki_cache) and os.unlink(ki_cache)
if KI_AUTO_CACHE:
cache_data = cache_ns(config_struct)
ns_list = cache_data.get(config, [])
else:
cmd = f"kubectl {KUBECTL_OPTIONS} get ns --no-headers --kubeconfig "+config
ns_list = [ e.split()[0] for e in get_data(cmd) ]
else:
cmd = f"kubectl {KUBECTL_OPTIONS} get ns --no-headers --kubeconfig "+config
ns_list = [ e.split()[0] for e in get_data(cmd) ]
ns = find_optimal(ns_list,ns_pattern)
if ns:
kubeconfig = config
break
if not KI_AUTO_SWITCH and n == 0:
if not ns and ns_dict == ki_ns_dict:
cmd = f"kubectl {KUBECTL_OPTIONS} get ns --no-headers --kubeconfig "+config
realtime_ns_list = [ e.split()[0] for e in get_data(cmd) ]
ns = find_optimal(realtime_ns_list,ns_pattern)
if ns:
kubeconfig = config
break
return ns,kubeconfig,switch,result_num
def cache_ns(config_struct: list):
from concurrent.futures import ThreadPoolExecutor, as_completed
if os.path.exists(ki_cool) and int(time.time() - os.stat(ki_cool).st_mtime) < CACHE_DURATION:
if os.path.exists(ki_ns_dict):
try:
with open(ki_ns_dict, 'r') as f:
return literal_eval(f.read())
except:
pass
open(ki_cool, "w").close()
print("\033[93mBuilding cache, please wait about 30s...\033[0m")
if not os.path.exists(ki_cache) or (os.path.exists(ki_cache) and int(time.time()-os.stat(ki_cache).st_mtime) > CACHE_DURATION):
open(ki_cache,"a").close()
d = {}
d_latest = {}
current_d = {}
current_config = os.path.realpath(session_config) if session_config and os.path.exists(session_config) else os.path.realpath(default_config)
cmd = f"kubectl {KUBECTL_OPTIONS} get ns --sort-by=.metadata.creationTimestamp --no-headers --kubeconfig " + current_config
l = get_data(cmd)
ns_list = [e.split()[0] for e in l]
current_d[current_config] = ns_list
with open(ki_current_ns_dict,'w') as f: f.write(str(current_d))
def check_ns(config, ns):
cmd = f"kubectl {KUBECTL_OPTIONS} get pod,cronjob --no-headers --kubeconfig {config} -n {ns}"
return bool(get_data(cmd))
def process_config(config):
cmd = f"kubectl {KUBECTL_OPTIONS} get ns --sort-by=.metadata.creationTimestamp --no-headers --kubeconfig " + config
retry_count = 0
max_retries = 2
while retry_count < max_retries:
l = get_data(cmd)
if l:
ns_list = [e.split()[0] for e in l]
latest_ns = l[-1].split()[0] if l else ""
valid_ns = []
with ThreadPoolExecutor(max_workers=min(10, len(ns_list))) as inner_executor:
futures = {inner_executor.submit(check_ns, config, ns): ns for ns in ns_list}
for future in as_completed(futures):
if future.result():
valid_ns.append(futures[future])
return config, valid_ns, latest_ns
else:
retry_count += 1
if retry_count == max_retries:
os.path.exists(config) and os.rename(config, config + "-NULL")
return config, [], ""
return config, [], ""
valid_configs = [cfg for cfg in config_struct[1] if os.path.exists(cfg) and 'config-sess-' not in cfg]
with ThreadPoolExecutor(max_workers=min(10, len(valid_configs))) as executor:
futures = [executor.submit(process_config, config) for config in valid_configs]
for future in as_completed(futures):
config, s, latest = future.result()
d[config] = s
if s:
d_latest[config] = latest
with open(ki_ns_dict,'w') as f: f.write(str(d))
with open(ki_latest_ns_dict,'w') as f: f.write(str(d_latest))
os.path.exists(ki_cache) and os.unlink(ki_cache)
return d
def switch_config(switch_num: int,k8s: str,ns: str,time: str):
switch = False
current_config = session_config if session_config and os.path.exists(session_config) else default_config
if os.path.exists(current_config) and os.environ['KUBECONFIG'] not in {current_config,os.path.realpath(current_config)}:
if current_config != os.path.realpath(current_config):
with open(ki_last,'w') as f: f.write(os.path.realpath(current_config))
os.unlink(current_config)
os.symlink(os.environ['KUBECONFIG'], current_config)
if os.path.exists(default_config):
os.unlink(default_config)
os.symlink(os.environ['KUBECONFIG'], default_config)
print("\033[1;93m{}\033[0m".format("[ "+time+" "+str(switch_num+1)+"-SWITCH ---> "+k8s+" / "+ns+" ] "))
find_history(os.environ['KUBECONFIG'],HISTORY_SCORE_DEFAULT)
switch_num > 0 and maybe_auto_cache()
switch = True
return switch
def get_data(cmd: str):
try:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
return p.stdout.readlines()
except:
sys.exit()
def maybe_auto_cache():
if KI_AUTO_CACHE:
subprocess.Popen("ki --c",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
def get_obj(ns: str,res: str,args='x'):
d = RESOURCE_TYPE_MAPPING
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" get pod "+res+" -o jsonpath='{.metadata.ownerReferences[0].kind}'"
l1 = res.split('-')
l2 = get_data(cmd)
obj = l2[0] if l2 else "Pod"
if obj in ("ReplicaSet","Deployment"):
if len(res) == 63:
del l1[-1:]
else:
del l1[-2:]
obj = "Deployment"
elif obj in ("StatefulSet","DaemonSet"):
del l1[-1:]
elif obj in ("Job"):
if '--' in res:
del l1[-3:]
else:
del l1[-1:]
name = ('-').join(l1)
if args[-1] in d.keys():
obj = d[args[-1]]
return obj,name
def get_feature(ns_list: list):
P = 177
MOD = 192073433
string_hashes = []
max_string_length = 0
for string in ns_list:
hashes = [0]
for i in range(len(string)):
hashes.append((hashes[-1] * P + ord(string[i])) % MOD)
string_hashes.append(hashes)
max_string_length = max(max_string_length, len(string))
pows = [1]
for i in range(max_string_length + 1):
pows.append(pows[-1] * P % MOD)
sorted_indices = list(range(len(ns_list)))
sorted_indices = sorted(sorted_indices, key=lambda i: len(ns_list[i]))
disabled_hashes = set()
answers = [None for _ in ns_list]
for i in sorted_indices:
string = ns_list[i]
hashes = string_hashes[i]
hash_to_be_disabled = []
min_length = len(string) + 1
for x in range(len(string)):
for y in range(x, len(string)):
substr_hash = (hashes[y + 1] - hashes[x] * pows[y + 1 - x]) % MOD
substr_hash = (substr_hash + MOD) % MOD
hash_to_be_disabled.append(substr_hash)
if substr_hash not in disabled_hashes and min_length > (y - x + 1):
min_length = y - x + 1
answers[i] = (x, y)
disabled_hashes.update(hash_to_be_disabled)
d = {}
for i, (x, y) in enumerate(answers):
d[ns_list[i]] = ns_list[i][x: y + 1]
return d
def info_w(k8s_path: str,result_lines: list):
current_config = os.path.realpath(session_config) if session_config and os.path.exists(session_config) else os.path.realpath(default_config)
l = k8s_path.split('/')
if 'K8S' in l:
if not os.path.exists(ki_lock) and len(l) > l.index('K8S')+1:
k8s_dir = l[l.index('K8S')+1]
if ( home+"/.kube/" + k8s_dir ) in result_lines or ( home+"/.kube/kubeconfig-" + k8s_dir ) in result_lines:
k8s_str = k8s_dir
else:
k8s_str = '-'.join(k8s_dir.split('-')[0:-1])
if result_lines:
config = find_optimal(result_lines,k8s_str) if k8s_str else None
if config and os.path.exists(session_config) and config not in {session_config,current_config}:
switch_kubeconfig(config)
print("\033[1;95m{}\033[0m".format("[ "+config.split("/")[-1]+" ]"))
else:
print("\033[1;38;5;208m{}\033[0m".format("[ "+current_config.split("/")[-1]+" ]"))
else:
print("\033[1;38;5;208m{}\033[0m".format("[ "+current_config.split("/")[-1]+(" (lock)" if os.path.exists(ki_lock) else "")+" ]"))
else:
print("\033[1;32m{}\033[0m".format("[ "+current_config.split("/")[-1]+" ]"))
os.path.exists(ki_lock) and int(time.time()-os.stat(ki_lock).st_mtime) > LOCK_TIMEOUT and os.unlink(ki_lock)
os.path.exists(ki_current_ns_dict) and int(time.time()-os.stat(ki_current_ns_dict).st_mtime) > NS_CACHE_DURATION and os.unlink(ki_current_ns_dict)
def info_k():
if os.path.exists(ki_pod_dict) and os.path.exists(ki_kube_dict):
with open(ki_pod_dict,'r') as f1, open(ki_kube_dict,'r') as f2:
dc1 = literal_eval(f1.read())
dc2 = literal_eval(f2.read())
for k in sorted(dc1):
most_used, second_most_used = get_most_used_pods(dc1[k])
most_recent = most_used if most_used else ""
second_recent = second_most_used if second_most_used else ""
print("{:<56}{:<32}{}".format(k, most_recent, second_recent))
for k in sorted(dc2.items(),key=lambda d:d[1]):
print("{:<56}{}".format(k[0].split('/')[-1],k[1]))
def get_most_used_pods(pod_history: list):
"""从最近32条记录中获取使用频率最高的2个pod"""
if not pod_history:
return None, None
# 只统计最近32条记录
recent_history = pod_history[-32:]
# 统计每个pod的使用次数
counter = Counter(recent_history)
most_common = counter.most_common(2)
# 返回使用次数最多的前2个pod
most_used = most_common[0][0] if len(most_common) >= 1 else None
# 如果只有1个pod,次常用也是它
second_most_used = most_common[1][0] if len(most_common) >= 2 else most_used
return most_used, second_most_used
def record(res: str,name: str,obj: str,cmd: str,kubeconfig: str,ns: str,config_struct: list):
l = os.environ['SSH_CONNECTION'].split() if 'SSH_CONNECTION' in os.environ else ['NULL','NULL','NULL']
USER = os.environ['USER'] if 'USER' in os.environ else "NULL"
HOST = l[2]
FROM = l[0]
key = kubeconfig+"/"+ns+"/"+("Pod" if obj in ('Deployment','StatefulSet','DaemonSet','ReplicaSet') else obj)
ki_file = time.strftime("%F",time.localtime())
with open(history+"/"+ki_file,'a+') as f: f.write( time.strftime("%F %T ",time.localtime())+"[ "+USER+"@"+HOST+" from "+FROM+" ---> "+kubeconfig+" ] " + cmd + "\n" )
dc = {}
if os.path.exists(ki_pod_dict) and os.path.getsize(ki_pod_dict) > 5:
with open(ki_pod_dict,'r') as f:
try:
dc = literal_eval(f.read())
dc_key_set = set(i.split('/')[0] for i in list(dc.keys()))
kubeconfig_set = set(i.split('/')[-1] for i in config_struct[1])
for i in dc_key_set - kubeconfig_set:
for j in dc.keys():
if i == j.split('/')[0]:
dc.pop(j,None)
# 将pod添加到历史记录(保存最多128个历史记录)
if key in dc:
# 如果dc[key]是旧格式(只有2个元素的列表),转换为新格式
if isinstance(dc[key], list) and len(dc[key]) <= 2:
dc[key] = list(dc[key]) # 保留旧数据
dc[key].append(name)
# 限制历史记录长度为128
if len(dc[key]) > 128:
dc[key] = dc[key][-128:]
else:
dc[key] = [name]
except:
os.unlink(ki_pod_dict)
else:
dc[key] = [name]
with open(ki_pod_dict,'w') as f: f.write(str(dc))
def analyze_cluster(stream=True):
"""分析集群状态并生成报告"""
import json
import requests
from datetime import datetime
print("\033[1;93m正在分析集群状态...\033[0m")
data = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"cluster_info": {},
"node_status": [],
"pod_status": {},
"resource_usage": {},
"events": []
}
try:
try:
version_output = get_data(f"kubectl {KUBECTL_OPTIONS} version -o json")
if version_output:
version_json = version_output[0].strip()
data["cluster_info"]["version"] = json.loads(version_json)
except:
data["cluster_info"]["version"] = "无法获取版本信息"
nodes = get_data(f"kubectl {KUBECTL_OPTIONS} get nodes -o wide")
if len(nodes) > 1:
for node in nodes[1:]:
node_info = node.split()
if len(node_info) >= 5:
data["node_status"].append({
"name": node_info[0],
"status": node_info[1],
"roles": node_info[2] if len(node_info) > 2 else "unknown",
"version": node_info[3] if len(node_info) > 3 else "unknown",
"internal_ip": node_info[5] if len(node_info) > 5 else "unknown"
})
ns_list = get_data(f"kubectl {KUBECTL_OPTIONS} get ns --no-headers")
for ns in ns_list:
ns_name = ns.split()[0]
pods = get_data(f"kubectl {KUBECTL_OPTIONS} get pods -n {ns_name} --no-headers")
running = 0
failed = 0
pending = 0
for pod in pods:
status = pod.split()[2]
if status == "Running":
running += 1
elif status in ["Failed", "Error", "CrashLoopBackOff"]:
failed += 1
elif status == "Pending":
pending += 1
data["pod_status"][ns_name] = {
"total": len(pods),
"running": running,
"failed": failed,
"pending": pending
}
for node in data["node_status"]:
try:
usage = get_data(f"kubectl {KUBECTL_OPTIONS} top node {node['name']}")
if len(usage) > 1:
usage_info = usage[1].split()
if len(usage_info) >= 5:
data["resource_usage"][node["name"]] = {
"cpu": usage_info[2],
"memory": usage_info[4]
}
except:
continue
events = get_data(f"kubectl {KUBECTL_OPTIONS} get events --sort-by=.metadata.creationTimestamp")
if events:
data["events"] = [event.strip() for event in events[-7:]]
if not KI_AI_KEY:
raise Exception("请设置 KI_AI_KEY 环境变量")
prompt = f"""请作为 Kubernetes 专家分析以下集群数据并生成简明扼要的健康状态报告:
集群信息:
- 时间戳: {data['timestamp']}
- 节点数量: {len(data['node_status'])}
- 命名空间数量: {len(data['pod_status'])}
节点状态:
{json.dumps(data['node_status'], indent=2, ensure_ascii=False)}
Pod 状态 (按命名空间,不含 Completed):
{json.dumps(data['pod_status'], indent=2, ensure_ascii=False)}
资源使用情况:
{json.dumps(data['resource_usage'], indent=2, ensure_ascii=False)}
最近事件:
{json.dumps(data['events'], indent=2, ensure_ascii=False)}
请提供:
1. 集群整体健康状况评估
2. 发现的潜在问题
3. 资源使用建议
4. 优化建议
"""
print("\n\033[1;32m集群健康状态报告:\033[0m")
response = requests.post(
f"{KI_AI_URL}",
headers={
"Authorization": f"Bearer {KI_AI_KEY}",
"Content-Type": "application/json"
},
json={
"model": KI_AI_MODEL,
"messages": [{
"role": "system",
"content": "你是一个经验丰富的 Kubernetes 集群分析专家。请基于提供的数据生成专业的分析报告。(忽略 Completed 状态的容器)"
}, {
"role": "user",
"content": prompt
}],
"temperature": 0.3,
"stream": stream
},
stream=stream
)
if response.status_code == 200:
if stream:
for line in response.iter_lines():
if line:
try:
json_response = json.loads(line.decode('utf-8').split('data: ')[1])
if 'choices' in json_response and len(json_response['choices']) > 0:
content = json_response['choices'][0].get('delta', {}).get('content', '')
if content:
print(content, end='', flush=True)
except:
continue
print()
else:
result = response.json()
print(result["choices"][0]["message"]["content"])
else:
print(f"\033[1;31mAI API 调用失败: {response.status_code}\033[0m")
print(response.text)
except Exception as e:
print(f"\033[1;31m分析过程中出错: {str(e)}\033[0m")
def chat_with_ai(question):
"""与 AI 进行对话,支持各种 IT 运维、开发相关需求"""
import json
import requests
import re
import os
from datetime import datetime
if not question:
print("\033[1;31m请输入问题内容\033[0m")
return
if not KI_AI_KEY:
print("\033[1;31m错误: 请设置 KI_AI_KEY 环境变量\033[0m")