-
Notifications
You must be signed in to change notification settings - Fork 10
/
k1s.py
executable file
·1159 lines (924 loc) · 36.4 KB
/
k1s.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/env python3
'''
TUI dashboard for Kubernetes resources
Example of use of kubernetes python module
NOTE: See https://github.com/kubernetes-client/python/blob/master/kubernetes/README.md for API specs, e.g. search for CoreV1APi, then for methods ...
'''
import os
import sys
import time
# For timestamp handling:
from datetime import datetime
import json
from kubernetes import client, config
NAME_FMT="32s"
INFO_FMT="60s"
NS_FMT="15s"
SHOW_TYPES=False
VERBOSE=False
nodes=[]
resources=[]
namespace='default'
#default_resources=["pods"]
default_resources=["all"]
DEFAULT_NAMESPACE='default'
## -- Get kubeconfig/cluster information: -------------------------
# Make sure ~/.kube/config is pointing to a valid cluster
HOME=os.getenv('HOME')
KUBECONFIG=os.getenv('KUBECONFIG')
DEFAULT_KUBECONFIG=HOME+'/.kube/config'
if KUBECONFIG is None:
KUBECONFIG=DEFAULT_KUBECONFIG
#config.load_kube_config()
if os.path.exists(KUBECONFIG):
print(f'Using KUBECONFIG={KUBECONFIG}')
config.load_kube_config(KUBECONFIG)
## -- Get context/namespace information: -------------------------
# {'context': {'cluster': 'kubernetes', 'namespace': 'k8scenario', 'user': 'kubernetes-admin'},
# 'name': 'k8scenario'}
contexts, active_context = config.list_kube_config_contexts()
if 'namespace' in active_context['context']:
DEFAULT_NAMESPACE=active_context['context']['namespace']
#print(active_context)
context=active_context['name']
print(f'context={context} namespace={DEFAULT_NAMESPACE}')
else:
print(f'No such kubeconfig file as "{KUBECONFIG}" - assuming in cluster')
config.load_incluster_config()
KUBECONFIG=None
context=None
#os.mkdir( '~/tmp', 0755 )
TMP_DIR = HOME + '/tmp'
if not os.path.exists(TMP_DIR):
os.mkdir( TMP_DIR )
## -- Get API clients: --------------------------------------------
corev1 = client.CoreV1Api()
appsv1 = client.AppsV1Api()
batchv1 = client.BatchV1Api()
#batchv1beta1 = client.BatchV1beta1Api()
batchv1 = client.BatchV1Api()
#============ COLOUR DEFINITIONS ==============================
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
BOLD_BLACK = '\033[30;1m'
BOLD_RED = '\033[31;1m'
BOLD_GREEN = '\033[32;1m'
BOLD_YELLOW = '\033[33;1m'
BOLD_BLUE = '\033[34;1m'
BOLD_MAGENTA = '\033[35;1m'
BOLD_CYAN = '\033[36;1m'
BOLD_WHITE = '\033[37;1m'
def black(msg):
''' return black ansi-coloured 'msg' text'''
return f"{BLACK}{msg}{RESET}"
def red(msg):
''' return red ansi-coloured 'msg' text'''
return f"{RED}{msg}{RESET}"
def green(msg):
''' return green ansi-coloured 'msg' text'''
return f"{GREEN}{msg}{RESET}"
def yellow(msg):
''' return yellow ansi-coloured 'msg' text'''
return f"{YELLOW}{msg}{RESET}"
def blue(msg):
''' return blue ansi-coloured 'msg' text'''
return f"{BLUE}{msg}{RESET}"
def magenta(msg):
''' return magenta ansi-coloured 'msg' text'''
return f"{MAGENTA}{msg}{RESET}"
def cyan(msg):
''' return cyan ansi-coloured 'msg' text'''
return f"{CYAN}{msg}{RESET}"
def white(msg):
''' return white ansi-coloured 'msg' text'''
return f"{WHITE}{msg}{RESET}"
def underline(msg):
''' return ansi-underlined 'msg' text'''
return f"{UNDERLINE}{msg}{RESET}"
def reset(msg):
''' reset ansi-colouring before 'msg' text'''
return f"{RESET}{msg}{RESET}"
def bold_black(msg):
''' return bold-black ansi-coloured 'msg' text'''
return f"{BOLD_BLACK}{msg}{RESET}"
def bold_red(msg):
''' return bold-red ansi-coloured 'msg' text'''
return f"{BOLD_RED}{msg}{RESET}"
def bold_green(msg):
''' return bold-green ansi-coloured 'msg' text'''
return f"{BOLD_GREEN}{msg}{RESET}"
def bold_yellow(msg):
''' return bold-yellow ansi-coloured 'msg' text'''
return f"{BOLD_YELLOW}{msg}{RESET}"
def bold_blue(msg):
''' return bold-blue ansi-coloured 'msg' text'''
return f"{BOLD_BLUE}{msg}{RESET}"
def bold_magenta(msg):
''' return bold-magenta ansi-coloured 'msg' text'''
return f"{BOLD_MAGENTA}{msg}{RESET}"
def bold_cyan(msg):
''' return bold-cyan ansi-coloured 'msg' text'''
return f"{BOLD_CYAN}{msg}{RESET}"
def bold_white(msg):
''' return bold-white ansi-coloured 'msg' text'''
return f"{BOLD_WHITE}{msg}{RESET}"
#print(red("Hello"),"there",blue("how"),"are you?")
#print(underline("Hello"),"there",green("how"),yellow("are you?"))
#= END OF === COLOUR DEFINITIONS ==============================
## -- Funcs: ---------------------------------------------------
def die(msg):
''' exit after printing bold-red error 'msg' text'''
print(f"die: { bold_red(msg) }")
sys.exit(1)
def sort_lines_by_age(op_lines):
''' sort 'op_lines' list using 'age' attribute of each line '''
sorted_op_lines = sorted(op_lines, key=lambda x: x['age'], reverse=True)
retstr = "\n"
for line in sorted_op_lines:
retstr += line['line']
return retstr
def set_hms(age_secs):
''' Build up a days-hours-mins-secs from provided {age_sec} secs '''
output=""
try:
if age_secs > 3600 * 24: # > 1d
days = int(age_secs / 3600 / 24)
age_secs = age_secs - (3600 * 24 * days)
output+=f"{days}d"
if age_secs > 3600: # > 1h
hours = int(age_secs / 3600)
age_secs = age_secs - (3600 * hours)
output+=f"{hours:02d}h"
if age_secs > 60: # > 1m
mins = int(age_secs / 60)
age_secs = age_secs - (60 * mins)
output+=f"{mins:02d}m"
output+=f"{age_secs:02}s"
return output.strip('0') # Strip of any leading zero
except:
return "-"
def write_json(response, json_file):
''' Write dump json {response} to {json_file} '''
with open(json_file, "w") as write_file:
json.dump(response, write_file, indent=2)
def write_json_items(items, file):
''' Write each json {item} to {file} '''
loop=1
for i in items:
jfile=file.replace("N.json", f'{loop}.json')
filed = open(jfile, 'w')
filed.write(str(i))
loop += 1
def get_age(i):
''' obtain {creation_time} age from {i.metadata} '''
creation_time = str(i.metadata.creation_timestamp)
if '+00:00' in creation_time:
creation_time = creation_time[ : creation_time.find('+00:00') ]
try:
time_str = datetime.strptime(creation_time, "%Y-%m-%d %H:%M:%S")
age_secs=time.mktime(time_str.timetuple())
time_str = datetime.now()
now_secs=time.mktime(time_str.timetuple())
age_secs=now_secs - age_secs
age_secs=int(age_secs)
except:
age_secs=0
return age_secs, set_hms(age_secs)
def get_image_info(instance):
image_list=[]
image_info=''
if hasattr(instance.spec, 'template'):
template_spec = instance.spec.template.spec
image_list=[ container.image for container in template_spec.containers ]
elif hasattr(instance.spec, 'job_template'):
template_spec = instance.spec.job_template.spec.template.spec
image_list=[ container.image for container in template_spec.containers ]
else:
image_list=[ container.image for container in instance.spec.containers ]
if len(image_list) > 0:
image_info = '[' + ','.join(image_list) + ']'
#items[0].spec.template.spec.containers[].image
#items[0].spec.containers[].image
return image_info
def get_replicas_info(instance):
''' get info about pod replicas for controller instance '''
spec_replicas=0
spec_parallelism=-1
if hasattr(instance.spec, 'replicas'):
spec_replicas=instance.spec.replicas
if hasattr(instance.spec, 'job_template'): # Jobs/CronJobs
spec_replicas=instance.spec.job_template.spec.completions
if spec_replicas == None:
spec_replicas=1
spec_parallelism=instance.spec.job_template.spec.parallelism
if spec_parallelism == None:
spec_parallelism=1
stat_replicas=0
if hasattr(instance.status, 'ready_replicas'):
stat_replicas=instance.status.ready_replicas
# This is for jobs/cronjobs - needs correcting
# TODO: show number of job pods active / total jobs
if hasattr(instance.status, 'active'):
active = instance.status.active
# print(f'type({active})={type(active)}\n')
if active == None:
stat_replicas=0
elif isinstance(active,int):
stat_replicas=active # isn't this an array of Object?
else:
print( stat_replicas )
stat_replicas=len(active)
#stat_replicas=instance.status.active # isn't this an array of Object?
#if instance.status.active:
jobs_extra=''
if spec_parallelism>=0:
jobs_extra=f'{spec_parallelism}/'
if stat_replicas == spec_replicas:
replicas_info=green(f'{stat_replicas}/{jobs_extra}{spec_replicas}')
else:
if stat_replicas is None:
stat_replicas = 0
replicas_info=yellow(f'{stat_replicas}/{jobs_extra}{spec_replicas}')
return replicas_info
def print_nodes():
''' print resource info '''
print(sprint_nodes())
def sprint_nodes():
''' build single-line representing resource info '''
res_type = 'nodes:' if SHOW_TYPES else ''
ret = corev1.list_node(watch=False)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/nodesN.json')
op_lines=[]
max_name_len=0
for i in ret.items:
node_name = i.metadata.name
if len(node_name) > max_name_len:
max_name_len=len(node_name)
name_format=f'<{max_name_len+12}s'
for i in ret.items:
node_ip = i.status.addresses[0].address
node_name = i.metadata.name
# Do node_name padding before adding ansi color chars:
#node_name = node_name + '-------'; node_name = node_name[0:8]
node_name = f'{node_name:{name_format}}'
taints = i.spec.taints
if taints and len(taints) != 0:
noexec=False
for taint in taints:
if hasattr(taint, 'effect') and taint.effect == 'NoExecute':
noexec=True
if noexec:
node_name = red(node_name)
else:
node_name = yellow(node_name)
age, age_hms = get_age(i)
line=f" {node_name:8s} { green( node_ip ) :24s} {age_hms}\n"
op_lines.append({'age': age, 'line': line})
return res_type + sort_lines_by_age(op_lines)
def get_nodes():
''' get list of node resources '''
l_nodes = {}
ret = corev1.list_node(watch=False)
for i in ret.items:
node_ip = i.status.addresses[0].address
node_name = i.metadata.name
l_nodes[node_ip] = node_name
return l_nodes
def print_pvcs(p_namespace='all'):
''' print resource info '''
print(sprint_pvcs(p_namespace))
def sprint_pvcs(p_namespace):
''' build single-line representing resource info '''
res_type = 'persistentvolumeclaims:' if SHOW_TYPES else ''
if p_namespace == 'all':
ret = corev1.list_persistent_volume_claim_for_all_namespaces(watch=False)
else:
ret = corev1.list_namespaced_persistent_volume_claim(watch=False, namespace=p_namespace)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/pvcsN.json')
max_name_len=5
max_sclass_len=5
for i in ret.items:
if len(i.metadata.name) > max_name_len:
max_name_len=len(i.metadata.name)
if i.spec.storage_class_name:
storage_class=i.spec.storage_class_name
if len(storage_class) > max_sclass_len:
max_sclass_len=len(storage_class)
name_sclass_fmt=f'{max_sclass_len+1}s'
name_fmt=f'{max_name_len+1}s'
op_lines=[]
for i in ret.items:
age, age_hms = get_age(i)
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
access_modes= str( i.status.access_modes )
if i.status.access_modes != None:
access_modes=",".join(i.status.access_modes)
#access_modes=",".join(i.status.access_modes)
storage_class=''
if i.spec.storage_class_name:
storage_class=i.spec.storage_class_name
#print(i.spec)
line = f' {ns_info} {i.metadata.name:{name_fmt}} {i.status.capacity["storage"]:6s} {access_modes} {i.status.phase:10s} <{storage_class:{name_sclass_fmt}}> {age_hms}\n'
op_lines.append( {'age': age, 'line': line} )
return res_type + sort_lines_by_age(op_lines)
#return (res_type + sort_lines_by_age(op_lines)).rstrip()
def print_pvs(p_namespace='all'):
''' print resource info '''
print(sprint_pvs(p_namespace))
def sprint_pvs(p_namespace):
''' build single-line representing resource info '''
res_type = 'persistentvolumes:' if SHOW_TYPES else ''
ret = corev1.list_persistent_volume(watch=False)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/pvsN.json')
max_name_len=5
max_claim_len=5
max_sclass_len=5
for i in ret.items:
if len(i.metadata.name) > max_name_len:
max_name_len=len(i.metadata.name)
if i.spec.claim_ref:
claimRef=i.spec.claim_ref
claim=f'{claimRef.namespace}/{claimRef.name}'
if len(claim) > max_claim_len:
max_claim_len=len(claim)
if i.spec.storage_class_name:
storage_class=i.spec.storage_class_name
if len(storage_class) > max_sclass_len:
max_sclass_len=len(storage_class)
name_fmt=f'{max_name_len+1}s'
name_claim_fmt=f'{max_claim_len+1}s'
name_sclass_fmt=f'{max_sclass_len+1}s'
op_lines=[]
for i in ret.items:
age, age_hms = get_age(i)
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
#print(i.spec)
policy=i.spec.persistent_volume_reclaim_policy
access_modes=",".join(i.spec.access_modes)
claim=''
if i.spec.claim_ref:
claimRef=i.spec.claim_ref
claim=f'{claimRef.namespace}/{claimRef.name}'
storage_class=''
if i.spec.storage_class_name:
storage_class=i.spec.storage_class_name
line = f' {ns_info} {i.metadata.name:{name_fmt}} {i.spec.capacity["storage"]:6s} {access_modes} {i.status.phase:10s} {claim:{name_claim_fmt}} <{storage_class:{name_sclass_fmt}}> {policy} {age_hms}\n'
op_lines.append( {'age': age, 'line': line} )
return res_type + sort_lines_by_age(op_lines)
#return (res_type + sort_lines_by_age(op_lines)).rstrip()
def print_pods(p_namespace='all'):
''' print resource info '''
print(sprint_pods(p_namespace)[:-1])
def sprint_pods(p_namespace='all'):
''' build single-line representing resource info '''
res_type = 'pods:' if SHOW_TYPES else ''
if p_namespace == 'all':
ret = corev1.list_pod_for_all_namespaces(watch=False)
else:
ret = corev1.list_namespaced_pod(watch=False, namespace=p_namespace)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/podsN.json')
op_lines=[]
for i in ret.items:
if i.metadata.labels:
if 'hide' in i.metadata.labels and i.metadata.labels['hide'] == 'k1spy':
continue
op_lines.append( get_pod_info(i, res_type, p_namespace) )
if len(op_lines) == 0:
return ''
#return (res_type + sort_lines_by_age(op_lines)).rstrip()
return res_type + sort_lines_by_age(op_lines)
def get_pod_host_info(i):
''' Get pod_ip and coloured host name (yellow if master node) '''
pod_ip = i.status.pod_ip
host_ip = i.status.host_ip
host = host_ip
if pod_ip is None:
pod_ip="-"
if host is None:
host="-"
if host_ip in nodes:
host = nodes[host_ip]
if host.find("ma") == 0:
host=cyan(host) # Colour master nodes
return(pod_ip, host)
def get_pod_scheduling_status(i):
''' Obtain pod_scheduling_status: from conditions '''
is_ready=False
is_scheduled=False
status = i.status.to_dict()
if 'conditions' in status:
if status['conditions']:
for cond in status['conditions']:
if 'type' in cond:
ctype = cond['type']
cstatus = cond['status']
if ctype == 'Ready' and cstatus == "True":
is_ready=True
if ctype == 'PodScheduled' and cstatus == "True":
is_scheduled=True
desired_actual_c = get_pod_desired_actual(status, is_ready, is_scheduled)
return (status, is_ready, is_scheduled, desired_actual_c)
def get_pod_desired_actual(status, is_ready, is_scheduled):
''' Obtain desired/actual containers '''
cexpected=0
if 'container_statuses' in status and status['container_statuses'] is not None:
cexpected=len( status['container_statuses'] )
cready=0
desired_actual_c=f'{cready}/{cexpected}'
if is_scheduled and is_ready:
try:
for cont_status in status['container_statuses']:
if 'ready' in cont_status and cont_status['ready']:
cready+=1
desired_actual_c=f'{cready}/{cexpected} '
except:
desired_actual_c=f'{cready}/{cexpected} '
if cready < cexpected:
desired_actual_c=yellow(desired_actual_c)
return desired_actual_c
def get_pod_status(i):
''' Obtain pod_status: desired/actual containers and status '''
phase=i.status.phase
ret_status=''
( status, is_ready, is_scheduled, desired_actual_c ) = get_pod_scheduling_status(i)
if is_scheduled and (not is_ready):
try:
container0 = status['container_statuses'][0] # !!
ret_status=container0['state']['terminated']['reason']
except:
try:
ret_status=container0['state']['waiting']['reason']
except:
ret_status='NonReady'
else:
ret_status=phase
if ret_status == "Running":
ret_status=green("Running")
if ret_status == "Complete":
ret_status=yellow("Running")
if hasattr(i.metadata,'deletion_timestamp'):
if i.metadata.deletion_timestamp:
ret_status = red("Terminating")
return (desired_actual_c, ret_status)
def get_pod_info(i, res_type, p_namespace='all'):
''' Obtain pod_info as a line and age from instance '''
(pod_ip, host) = get_pod_host_info(i)
(desired_actual_c, pod_status) = get_pod_status(i)
image_info = get_image_info(i)
age, age_hms = get_age(i)
if VERBOSE: # Checking for unset vars
print(f"namespace={i.metadata.namespace:{NS_FMT}}")
print(f"type/name={res_type}{i.metadata.name:{NAME_FMT}}")
print(f"pod_status={pod_status}")
print(f"pod_ip/host={pod_ip:15s}/{host}\n")
print(f"creation_time={i.metadata.creation_time}")
print(f"image_info={image_info}\n")
print(f"age={age_hms}\n")
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
pod_host_age = f'{pod_ip:15s}/{host:10s} {age_hms}'
pod_info = f'{pod_status:20s} {pod_host_age} {image_info}'
line = f' {ns_info} {i.metadata.name:{NAME_FMT}} {desired_actual_c} {pod_info}\n'
return {'age': age, 'line': line}
def print_deployments(p_namespace='all'):
''' print resource info '''
print(sprint_deployments(p_namespace))
def sprint_deployments(p_namespace='all'):
''' build single-line representing resource info '''
res_type = 'deployments:' if SHOW_TYPES else ''
if p_namespace == 'all':
ret = appsv1.list_deployment_for_all_namespaces(watch=False)
else:
ret = appsv1.list_namespaced_deployment(watch=False, namespace=p_namespace)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/deploysN.json')
op_lines=[]
for i in ret.items:
info=get_replicas_info(i)
image_info = get_image_info(i)
age, age_hms = get_age(i)
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
line = f" {ns_info} {i.metadata.name:{NAME_FMT}} {info:{INFO_FMT}} {age_hms} {image_info}\n"
op_lines.append({'age': age, 'line': line})
return res_type + sort_lines_by_age(op_lines)
def print_daemon_sets(p_namespace='all'):
''' print resource info '''
print(sprint_daemon_sets(p_namespace))
def sprint_daemon_sets(p_namespace='all'):
''' build single-line representing resource info '''
#res_type = 'ds/' if SHOW_TYPES else ''
res_type = 'daemonsets:' if SHOW_TYPES else ''
if p_namespace == 'all':
ret = appsv1.list_daemon_set_for_all_namespaces(watch=False)
else:
ret = appsv1.list_namespaced_daemon_set(watch=False, namespace=p_namespace)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/dsetsN.json')
op_lines=[]
for i in ret.items:
image_info = get_image_info(i)
age, age_hms = get_age(i)
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
line = f" {ns_info} {i.metadata.name:{NAME_FMT}} {age_hms} {image_info}\n"
op_lines.append({'age': age, 'line': line})
return res_type + sort_lines_by_age(op_lines)
def print_stateful_sets(p_namespace='all'):
''' print resource info '''
print(sprint_stateful_sets(p_namespace))
def sprint_stateful_sets(p_namespace='all'):
''' build single-line representing resource info '''
#res_type = 'ss/' if SHOW_TYPES else ''
res_type = 'statefulsets:' if SHOW_TYPES else ''
if p_namespace == 'all':
ret = appsv1.list_stateful_set_for_all_namespaces(watch=False)
else:
ret = appsv1.list_namespaced_stateful_set(watch=False, namespace=p_namespace)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/ssetsN.json')
op_lines=[]
for i in ret.items:
info=get_replicas_info(i)
image_info = get_image_info(i)
age, age_hms = get_age(i)
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
line = f" {ns_info} {i.metadata.name:{NAME_FMT}} {info:56} {age_hms} {image_info}\n"
op_lines.append({'age': age, 'line': line})
return res_type + sort_lines_by_age(op_lines)
def print_replica_sets(p_namespace='all'):
''' print resource info '''
print(sprint_replica_sets(p_namespace))
def sprint_replica_sets(p_namespace='all'):
''' build single-line representing resource info '''
#res_type = 'rs/' if SHOW_TYPES else ''
res_type = 'replicasets:' if SHOW_TYPES else ''
if p_namespace == 'all':
ret = appsv1.list_replica_set_for_all_namespaces(watch=False)
else:
ret = appsv1.list_namespaced_replica_set(watch=False, namespace=p_namespace)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/repsetsN.json')
op_lines=[]
for i in ret.items:
info=get_replicas_info(i)
image_info = get_image_info(i)
age, age_hms = get_age(i)
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
line = f" {ns_info} {i.metadata.name:{NAME_FMT}} {info:{INFO_FMT}} {age_hms} {image_info}\n"
op_lines.append({'age': age, 'line': line})
return res_type + sort_lines_by_age(op_lines)
def print_services(p_namespace='all'):
''' print resource info '''
print(sprint_services(p_namespace))
def get_endpoints(p_svc_name, p_namespace):
# See: https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md#list_namespaced_endpoints
ret = corev1.list_namespaced_endpoints(watch=False, namespace=p_namespace)
for i in ret.items:
if i.metadata.name == p_svc_name:
#print(i.subsets[0])
#print(i.subsets[0].addresses)
#print(i.subsets[0].not_ready_addresses)
if i.subsets != None:
ready_ep=i.subsets[0].addresses
unready_ep=i.subsets[0].not_ready_addresses
if ready_ep == None: ready_ep=[]
if unready_ep == None: unready_ep=[]
return(ready_ep, unready_ep)
#sys.exit()
#return [99]
return ([],[])
def sprint_services(p_namespace='all'):
''' build single-line representing resource info '''
res_type = 'services:' if SHOW_TYPES else ''
if p_namespace == 'all':
ret = corev1.list_service_for_all_namespaces(watch=False)
else:
ret = corev1.list_namespaced_service(watch=False, namespace=p_namespace)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/servicesN.json')
op_lines=[]
for i in ret.items:
port=""
spec = i.spec.to_dict()
ext_ips=[]
if i.status.load_balancer:
lb=i.status.load_balancer
if lb.ingress:
for ingress in lb.ingress:
ext_ips.append( ingress.ip )
# If not ip in status, use static spec: todo - compare with kubectl output
if not ext_ips:
ext_ips=spec['external_i_ps']
if ext_ips:
# Convert list to string:
ext_ips=','.join(ext_ips)
else:
ext_ips='Pending'
if spec and 'ports' in spec and spec['ports'] and 'node_port' in spec['ports'][0]:
port0=spec['ports'][0]
if 'node_port' in port0 and port0['node_port'] is not None:
port=f" {port0['port']}:{port0['node_port']}"
else:
port=f" {port0['port']}"
port += f"/{port0['protocol']}"
cluster_ip=spec['cluster_ip']
if not cluster_ip:
cluster_ip=''
#policy=""
age, age_hms = get_age(i)
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
endpoint_addresses = get_endpoints(i.metadata.name, i.metadata.namespace)
num_ready_ep_addresses = len(endpoint_addresses[0])
num_notready_ep_addresses = len(endpoint_addresses[1])
endpoints_info=f'{num_ready_ep_addresses}/{num_ready_ep_addresses + num_notready_ep_addresses}'
#svc_info = f'{cluster_ip:14s} {svc_type:12s} {ext_ips:15s} {port:14s}{policy:8s} {age_hms}'
svc_info = f'{cluster_ip:14s} {spec["type"]:12s} {ext_ips:15s} {port:14s} eps:{endpoints_info} {age_hms}'
line = f' {ns_info} {i.metadata.name:{NAME_FMT}} {svc_info}\n'
op_lines.append({'age': age, 'line': line})
return res_type + sort_lines_by_age(op_lines)
def print_jobs(p_namespace='all'):
''' print resource info '''
print(sprint_jobs(p_namespace))
def sprint_jobs(p_namespace='all'):
''' build single-line representing resource info '''
#res_type = 'job/' if SHOW_TYPES else ''
res_type = 'jobs:' if SHOW_TYPES else ''
if p_namespace == 'all':
ret = batchv1.list_job_for_all_namespaces(watch=False)
else:
ret = batchv1.list_namespaced_job(watch=False, namespace=p_namespace)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/jobsN.json')
op_lines=[]
for i in ret.items:
info=get_replicas_info(i)
image_info = get_image_info(i)
age, age_hms = get_age(i)
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
line = f" {ns_info} {i.metadata.name:{NAME_FMT}} {info} {age_hms} {image_info}\n"
op_lines.append({'age': age, 'line': line})
return res_type + sort_lines_by_age(op_lines)
def print_cron_jobs(p_namespace='all'):
''' print resource info '''
print(sprint_cron_jobs(p_namespace))
def sprint_cron_jobs(p_namespace='all'):
''' build single-line representing resource info '''
#res_type = 'cronjob/' if SHOW_TYPES else ''
res_type = 'cronjobs:' if SHOW_TYPES else ''
if p_namespace == 'all':
ret = batchv1.list_cron_job_for_all_namespaces(watch=False)
else:
ret = batchv1.list_namespaced_cron_job(watch=False, namespace=p_namespace)
if len(ret.items) == 0:
return ''
write_json_items(ret.items, TMP_DIR + '/cronjobsN.json')
op_lines=[]
for i in ret.items:
info=get_replicas_info(i)
image_info = get_image_info(i)
age, age_hms = get_age(i)
ns_info=''
if p_namespace == 'all':
ns_info=f'[{i.metadata.namespace:{NS_FMT}}] '
line = f" {ns_info} {i.metadata.name:{NAME_FMT}} {info} {age_hms} {image_info}\n"
op_lines.append({'age': age, 'line': line})
return res_type + sort_lines_by_age(op_lines)
def test_methods():
''' test print and sprintf methods '''
print("======== Listing nodes with their IPs:")
print_nodes()
print("======== [all namespaces] Listing pods with their IPs:")
print_pods()
print("---- [namespace='default'] Listing pods with their IPs:")
print_pods(p_namespace='default')
print("======== [all namespaces] Listing deployments:")
print_deployments()
print("---- [namespace='default'] Listing deployments:")
print_deployments(p_namespace='default')
print("======== [all namespaces] Listing daemon_sets:")
print_daemon_sets()
print("---- [namespace='default'] Listing daemon_sets:")
print_daemon_sets(p_namespace='default')
print("======== [all namespaces] Listing stateful_sets:")
print_stateful_sets()
print("---- [namespace='default'] Listing stateful_sets:")
print_stateful_sets(p_namespace='default')
print("======== [all namespaces] Listing replica_sets:")
print_replica_sets()
print("---- [namespace='default'] Listing replica_sets:")
print_replica_sets(p_namespace='default')
print("======== [all namespaces] Listing stateful_sets:")
print_stateful_sets()
print("---- [namespace='default'] Listing stateful_sets:")
print_stateful_sets(p_namespace='default')
print("======== [all namespaces] Listing services:")
print_services()
print("---- [namespace='default'] Listing services:")
print_services(p_namespace='default')
print("======== [all namespaces] Listing jobs:")
print_jobs()
print("---- [namespace='default'] Listing jobs:")
print_jobs(p_namespace='default')
print("======== [all namespaces] Listing cron_jobs:")
print_cron_jobs()
print("---- [namespace='default'] Listing cron_jobs:")
print_cron_jobs(p_namespace='default')
def namespace_exists(p_namespace):
''' check if namespace exists - or True if 'all' specified '''
if p_namespace == "all":
return True
ret = corev1.list_namespace(watch=False)
for i in ret.items:
if i.metadata.name == p_namespace:
return True
return False
def build_context_namespace_resources_info(p_context, p_namespace, p_resources):
if context:
''' convenience: build up context status line '''
pr_context=f'{ bold_white("Context:") } { bold_green(p_context) }'
else:
pr_context=f'{ bold_white("Context:") } { bold_green("in-cluster") }'
#pr_resources=f'{ bold_white("Resources:") } { bold_green(p_resources) }'
pr_resources=f'{ bold_white("Resources:") } { bold_green( ",".join(p_resources)) }'
if namespace_exists(p_namespace):
pr_namespace=f'{ bold_white("Namespace:") } { bold_green(p_namespace) }'
else:
pr_namespace=f'{ bold_white("Namespace:") } { bold_red(p_namespace) }'
return f'{ pr_context } / { pr_namespace } / { pr_resources }'
def cls():
''' clear screen '''
sys.stdout.write('\033[H\033[J')
def main_setup(p_resources, p_namespace):
''' Normalize resources/namespace argument values '''
final_resources=[]
for reslist in p_resources:
if "," in reslist:
resource_list = reslist.split(",")
final_resources.extend(resource_list)
else:
resource_list = reslist