-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathki.py
executable file
·1402 lines (1305 loc) · 64.6 KB
/
ki.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
#*************************************************
# Description : Kubectl Pro
# Version : 5.6
#*************************************************
from collections import deque
import os,re,sys,time,readline,subprocess
#-----------------VAR-----------------------------
home = os.environ["HOME"]
history = home + "/.history"
default_config = home + "/.kube/config"
ki_all = history + "/.all"
ki_dict = history + "/.dict"
ki_last = history + "/.last"
ki_lock = history + "/.lock"
ki_line = history + "/.line"
ki_cache = history + "/.cache"
ki_unlock = history + "/.unlock"
ki_ns_dict = history + "/.ns_dict"
ki_pod_dict = history + "/.pod_dict"
ki_latest_ns_dict = history + "/.latest_ns_dict"
ki_current_ns_dict = history + "/.current_ns_dict"
KUBECTL_OPTIONS = "--insecure-skip-tls-verify"
KI_AI_URL = os.getenv("KI_AI_URL", "https://api.openai.com/v1/chat/completions")
KI_AI_KEY = os.getenv("KI_AI_KEY", "")
KI_AI_MODEL = os.getenv("KI_AI_MODEL", "gpt-4o")
#-----------------FUN-----------------------------
def cmp_file(f1, f2):
if os.path.getsize(f1) != os.path.getsize(f2):
return False
bufsize = 8192
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"):
action2 = ""
if args in ("cle","delete"):
if confirm_action("This command will delete the "+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 > "+res+"."+obj.lower()+".yml"
else:
action = "get"
cmd = f"kubectl {KUBECTL_OPTIONS} -n "+ns+" "+action+" "+obj.lower()+" "+res+action2 if obj not in ("PersistentVolume") else f"kubectl {KUBECTL_OPTIONS} "+action+" "+obj.lower()+" "+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 = {'d':'Deployment','s':'Service','i':'Ingress','f':'StatefulSet','a':'DaemonSet','p':'Pod','g':'Gateway','h':'HTTPRoute','V':'VirtualService','D':'DestinationRule','E':'EnvoyFilter'}
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) * 0.618 if has_namespace[i] else 8192 for i, row in enumerate(namespace_list)]
contain_scores = [len(row.replace(namespace, '')) * 0.618 for row in namespace_list]
result_scores = [(index_scores[i] + container) * (1 if has_namespace[i] else 1.618) 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():
os.path.exists(history) or os.mkdir(history)
cmd = '''find $HOME/.kube -maxdepth 2 -type f -name 'kubeconfig*' -a ! -name 'kubeconfig-*-NULL' 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` )'''
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:
if os.path.exists(default_config):
if not os.path.islink(default_config):
os.rename(default_config, home+"/.kube/config-0")
os.symlink(home+"/.kube/config-0",default_config)
kubeconfig = "config-0"
else:
kubeconfig = result_lines[0].split("/")[-1]
else:
try:
os.unlink(default_config)
except:
pass
os.symlink(result_lines[0],default_config)
kubeconfig = result_lines[0].split("/")[-1]
elif result_num > 1:
global header_config
dc = {}
if os.path.exists(ki_dict) and os.path.getsize(ki_dict) > 5:
with open(ki_dict,'r') as f:
try:
dc = eval(f.read())
for config in list(dc.keys()):
if not os.path.exists(config):
del dc[config]
except:
os.unlink(ki_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(default_config)
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(default_config):
if not os.path.islink(default_config):
os.rename(default_config, home+"/.kube/config-0")
os.symlink(home+"/.kube/config-0",default_config)
kubeconfig = "config-0"
else:
for e in result_lines:
if cmp_file(e,default_config): kubeconfig = e.strip().split("/")[-1]
else:
try:
os.unlink(default_config)
except:
pass
os.symlink(result_lines[0],default_config)
kubeconfig = result_lines[0].split("/")[-1]
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=1):
if config != header_config:
dc = {}
if os.path.exists(ki_dict) and os.path.getsize(ki_dict) > 5:
with open(ki_dict,'r') as f:
dc = eval(f.read())
dc[config] = dc[config] + num if config in dc else 1
dc.pop(default_config,None)
for config in list(dc.keys()):
if not os.path.exists(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_dict,'w') as f: f.write(str(dc))
def get_config(config_lines: list, ns: str):
history_lines = []
if os.path.exists(ki_dict):
with open(ki_dict, 'r') as f:
dc = eval(f.read())
dc.pop(os.path.realpath(default_config), None)
history_lines = [k[0] for k in sorted(dc.items(), key=lambda d: d[1], reverse=True)]
config_lines.remove(os.path.realpath(default_config))
matching_configs = [config for config in config_lines if ns in config]
if not matching_configs:
return default_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]
if os.path.exists(ki_current_ns_dict) and int(time.time()-os.stat(ki_current_ns_dict).st_mtime) < 300:
with open(ki_current_ns_dict) as f:
try:
d = eval(f.read())
current_config = os.path.realpath(default_config)
if current_config in d:
ns_list = d[current_config]
if find_optimal(ns_list,ns_pattern):
ns_dict = ki_current_ns_dict
config_struct[1] = [current_config]
except:
os.path.exists(ki_cache) and os.unlink(ki_cache)
ns_list = cache_ns(config_struct)[config]
config = get_config(config_struct[1], kn[0]) or default_config if len(kn) > 1 else default_config
if len(config_struct[1]) > 1:
current_config = os.path.realpath(config)
config_struct[1] = deque(config_struct[1])
current_config in config_struct[1] and config_struct[1].remove(current_config)
config_struct[1].appendleft(current_config)
for n,config in enumerate(config_struct[1]):
if os.path.exists(ns_dict):
with open(ns_dict,'r') as f:
try:
d = eval(f.read())
ns_list = d[config]
except:
os.path.exists(ki_cache) and os.unlink(ki_cache)
ns_list = cache_ns(config_struct)[config]
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
return ns,kubeconfig,switch,result_num
def cache_ns(config_struct: list):
if not os.path.exists(ki_cache) or ( os.path.exists(ki_cache) and int(time.time()-os.stat(ki_cache).st_mtime) > 1800 ):
open(ki_cache,"a").close()
d = {}
d_latest = {}
current_d = {}
current_config = 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))
for config in config_struct[1]:
s = []
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 ]
if os.path.exists(ki_all):
s = ns_list
else:
for ns in ns_list:
cmd1 = f"kubectl {KUBECTL_OPTIONS} get pod --no-headers --kubeconfig "+config+" -n "+ns
cmd2 = f"kubectl {KUBECTL_OPTIONS} get cronjob --no-headers --kubeconfig "+config+" -n "+ns
if get_data(cmd1) or get_data(cmd2):
s.append(ns)
d[config] = s
d_latest[config] = l[-1].split()[0]
break
else:
retry_count += 1
if retry_count == max_retries:
os.path.exists(config) and os.rename(config, config + "-NULL")
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
if os.path.exists(default_config) and os.environ['KUBECONFIG'] not in {default_config,os.path.realpath(default_config)}:
if default_config != os.path.realpath(default_config):
with open(ki_last,'w') as f: f.write(os.path.realpath(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'],3)
switch_num > 0 and subprocess.Popen("ki --c",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
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 get_obj(ns: str,res: str,args='x'):
d = {'s':"Service",'i':"Ingress"}
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):
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(default_config) and config not in {default_config,os.path.realpath(default_config)}:
os.unlink(default_config)
os.symlink(config,default_config)
print("\033[1;95m{}\033[0m".format("[ "+config.split("/")[-1]+" ]"))
else:
print("\033[1;38;5;208m{}\033[0m".format("[ "+os.path.realpath(default_config).split("/")[-1]+" ]"))
else:
print("\033[1;38;5;208m{}\033[0m".format("[ "+os.path.realpath(default_config).split("/")[-1]+(" (lock)" if os.path.exists(ki_lock) else "")+" ]"))
else:
print("\033[1;32m{}\033[0m".format("[ "+os.path.realpath(default_config).split("/")[-1]+" ]"))
os.path.exists(ki_lock) and int(time.time()-os.stat(ki_lock).st_mtime) > 3600 and os.unlink(ki_lock)
os.path.exists(ki_current_ns_dict) and int(time.time()-os.stat(ki_current_ns_dict).st_mtime) > 300 and os.unlink(ki_current_ns_dict)
def info_k():
if os.path.exists(ki_pod_dict) and os.path.exists(ki_dict):
with open(ki_pod_dict,'r') as f1, open(ki_dict,'r') as f2:
dc1 = eval(f1.read())
dc2 = eval(f2.read())
for k in sorted(dc1):
print("{:<56}{:<32}{}".format(k,dc1[k][0],dc1[k][1]))
for k in sorted(dc2.items(),key=lambda d:d[1]):
print("{:<56}{}".format(k[0].split('/')[-1],k[1]))
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 = 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)
name_dc = dict(dc[key][1]) if key in dc else {}
name_dc[name] = name_dc[name] + 1 if name in name_dc else 1
name_dc = sorted(name_dc.items(),key = lambda name_dc:(name_dc[1], name_dc[0]),reverse=True)
if len(name_dc) > 5: del name_dc[5:]
dc[key] = [name,name_dc]
except:
os.unlink(ki_pod_dict)
else:
dc[key] = [name,[(name,1)]]
with open(ki_pod_dict,'w') as f: f.write(str(dc))
def analyze_cluster():
"""分析集群状态并生成报告"""
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"
})
# 获取所有命名空间的 Pod 状态
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[-5:]] # 最近5个事件
# 调用 AI API 分析数据
if not KI_AI_KEY:
raise Exception("请设置 KI_AI_KEY 环境变量")
# 准备发送给 AI 的提示信息
prompt = f"""请作为 Kubernetes 专家分析以下集群数据并生成简明扼要的健康状态报告:
集群信息:
- 时间戳: {data['timestamp']}
- 节点数量: {len(data['node_status'])}
- 命名空间数量: {len(data['pod_status'])}
节点状态:
{json.dumps(data['node_status'], indent=2, ensure_ascii=False)}
Pod 状态 (按命名空间):
{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. 优化建议
"""
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 集群分析专家。请基于提供的数据生成专业的分析报告。"
}, {
"role": "user",
"content": prompt
}],
"temperature": 0.3
}
)
if response.status_code == 200:
result = response.json()
print("\n\033[1;32m集群健康状态报告:\033[0m")
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 analyze_cluster_stream():
"""分析集群状态并生成报告"""
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"
})
# 获取所有命名空间的 Pod 状态
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:]]
# 调用 AI API 分析数据
if not KI_AI_KEY:
raise Exception("请设置 KI_AI_KEY 环境变量")
# 准备发送给 AI 的提示信息
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": True
},
stream=True
)
if response.status_code == 200:
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:
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")
return
try:
print("\033[1;93m思考中...\033[0m")
# 让 AI 分析问题类型和是否需要生成文件
pre_check_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": """你是一个 IT 专家。请分析用户的问题并返回 JSON 格式的结果:
{
"type": "配置|代码|脚本|其他",
"needs_file": true|false,
"language": "yaml|k8s|golang|python|shell|rust|...",
"description": "简短描述这个问题的类型和目的"
}"""
}, {
"role": "user",
"content": question
}],
"temperature": 0.1,
}
)
question_type = {"needs_file": False}
if pre_check_response.status_code == 200:
try:
question_type = json.loads(pre_check_response.json()['choices'][0]['message']['content'])
except:
pass
# 根据问题类型设置不同的系统提示
if question_type["needs_file"]:
system_prompt = f"""你是一个专业的 IT 专家。对于{question_type["description"]}类问题:
1. 首先用 JSON 格式提供文件元数据:
```json
{{
"files": [
{{
"name": "文件名(不含路径和时间戳)",
"type": "{question_type["language"]}",
"description": "这个文件的用途描述"
}}
]
}}
```
2. 然后解释主要实现思路和关键点
3. 提供完整的代码或配置,使用对应的代码块标记,例如:
```{question_type["language"]}
// 代码内容
```
4. 最后提供使用说明或测试方法
注意:
- 文件名应该反映代码或配置的用途
- 代码需要包含必要的注释
- 配置文件需要包含关键配置项的说明"""
else:
system_prompt = "你是一个专业的 IT 专家,请针对问题提供详细的解答和建议。"
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": system_prompt
}, {
"role": "user",
"content": question
}],
"temperature": 0.3,
"stream": True
},
stream=True
)
if response.status_code == 200: