-
Notifications
You must be signed in to change notification settings - Fork 3
/
cmu
executable file
·10418 lines (9195 loc) · 456 KB
/
cmu
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
#! /bin/sh
# vim: ts=4 filetype=python expandtab shiftwidth=4 softtabstop=4 syntax=python
''''eval version=$( ls /usr/bin/python3.* | \
grep '.*[0-9]$' | sort -nr -k2 -t. | head -n1 ) && \
version=${version##/usr/bin/python3.} && [ ${version} ] && \
[ ${version} -ge 9 ] && exec /usr/bin/python3.${version} "$0" "$@" || \
exec /usr/bin/env python3 "$0" "$@"' #'''
# The above hack is to handle distros where /usr/bin/python3
# doesn't point to the latest version of python3 they provide
# Requires: ansible
# Requires: python3 (>= 3.9)
# Requires: python3-natsort
# Requires: python3-openssl
# Recommends: python3-ujson
#
# Copyright the Cluster Management Toolkit for Kubernetes contributors.
# SPDX-License-Identifier: MIT
# pylint: disable=too-many-lines
import ast
import base64
import binascii
import copy
import curses
from curses import wrapper
from datetime import datetime, timezone
import errno
from getpass import getuser
import http.client
# ujson is much faster than json,
# but it might not be available
try: # pragma: no cover
import ujson as json
# The exception raised by ujson when parsing fails is different
# from what json raises
DecodeException = ValueError
except ModuleNotFoundError: # pragma: no cover
import json # type: ignore
DecodeException = json.decoder.JSONDecodeError # type: ignore
from operator import itemgetter
import os
from pathlib import Path
import re
import socket
import subprocess # nosec
from subprocess import PIPE, STDOUT # nosec
import sys
from typing import Any, cast, Optional, Type, Union
from collections.abc import Callable
try:
import yaml
except ModuleNotFoundError: # pragma: no cover
sys.exit("ModuleNotFoundError: Could not import yaml; "
"you may need to (re-)run `cmt-install` or `pip3 install PyYAML`; aborting.")
try:
from natsort import natsorted
except ModuleNotFoundError: # pragma: no cover
sys.exit("ModuleNotFoundError: Could not import natsort; "
"you may need to (re-)run `cmt-install` or `pip3 install natsort`; aborting.")
from clustermanagementtoolkit.cmttypes import deep_get, deep_get_with_fallback
from clustermanagementtoolkit.cmttypes import deep_get_str_tuple_paths, deep_set, DictPath
from clustermanagementtoolkit.cmttypes import FilePath, Retval
from clustermanagementtoolkit.cmttypes import SecurityPolicy, SecurityStatus, StatusGroup
from clustermanagementtoolkit.cmttypes import ProgrammingError, FilePathAuditError
from clustermanagementtoolkit import cmtpaths
from clustermanagementtoolkit.cmtpaths import BINDIR, KUBE_CONFIG_FILE, HOMEDIR, DEPLOYMENT_DIR
from clustermanagementtoolkit.cmtpaths import CMT_CONFIG_FILE_DIR, THEME_DIR
from clustermanagementtoolkit.cmtpaths import DEFAULT_THEME_FILE
from clustermanagementtoolkit.cmtpaths import ANSIBLE_PLAYBOOK_DIR, SYSTEM_ANSIBLE_PLAYBOOK_DIR
from clustermanagementtoolkit.cmtpaths import CMT_CONFIG_FILE_DIRNAME, CMT_CONFIG_FILE
from clustermanagementtoolkit.cmtpaths import CMT_CONFIG_FILENAME
from clustermanagementtoolkit.cmtpaths import SSH_ARGS_RELAXED, SSH_ARGS_STRICT, SSH_BIN_PATH
from clustermanagementtoolkit import cmtio
from clustermanagementtoolkit.cmtio import execute_command
from clustermanagementtoolkit.cmtio import expand_path
from clustermanagementtoolkit.cmtio import secure_read_string, secure_which, secure_write_string
from clustermanagementtoolkit.cmtio_yaml import secure_read_yaml
# from cmtlog import auditlog, debuglog, CMTLogType, CMTLog
# from cmtlog import debuglog, CMTLogType, CMTLog
from clustermanagementtoolkit.cmtvalidators import validate_name
from clustermanagementtoolkit.commandparser import parse_commandline
from clustermanagementtoolkit.logparser import logparser, logparser_initialised
from clustermanagementtoolkit.logparser import LogLevel, LogparserConfiguration
from clustermanagementtoolkit.logparser import lvl_to_letter_severity, lvl_to_4letter_severity
from clustermanagementtoolkit.logparser import lvl_to_word_severity
from clustermanagementtoolkit.logparser import loglevel_to_name, get_loglevel_names
from clustermanagementtoolkit.logparser import name_to_loglevel, get_parser_list
from clustermanagementtoolkit import curses_helper
from clustermanagementtoolkit import cmtlib
from clustermanagementtoolkit.cmtlib import decode_value, clamp, get_package_versions
from clustermanagementtoolkit.cmtlib import identify_k8s_distro
from clustermanagementtoolkit.cmtlib import make_label_selector
from clustermanagementtoolkit.cmtlib import none_timestamp, timestamp_to_datetime
from clustermanagementtoolkit.cmtlib import split_msg, versiontuple, read_cmtconfig, substitute_list
from clustermanagementtoolkit.cmtlib import check_allowlist
from clustermanagementtoolkit.curses_helper import CursesConfiguration, color_log_severity
from clustermanagementtoolkit.curses_helper import format_helptext, get_mousemask
from clustermanagementtoolkit.curses_helper import color_status_group
from clustermanagementtoolkit.curses_helper import UIProps, WidgetLineAttrs
from clustermanagementtoolkit.curses_helper import get_theme_ref, read_theme
from clustermanagementtoolkit.curses_helper import themearray_wrap_line, themearray_to_string
from clustermanagementtoolkit.curses_helper import themearray_len
from clustermanagementtoolkit.curses_helper import themearray_truncate
from clustermanagementtoolkit.curses_helper import ThemeAttr, ThemeRef, ThemeStr
from clustermanagementtoolkit import listgetters
from clustermanagementtoolkit.listgetters import listgetter_allowlist
from clustermanagementtoolkit import listgetters_async
from clustermanagementtoolkit.listgetters_async import listgetter_async_allowlist
from clustermanagementtoolkit import datagetters
from clustermanagementtoolkit import generators
from clustermanagementtoolkit.generators import generator_allowlist, default_processor
from clustermanagementtoolkit import infogetters
from clustermanagementtoolkit.infogetters import infogetter_allowlist
from clustermanagementtoolkit import itemgetters
from clustermanagementtoolkit.itemgetters import itemgetter_allowlist
from clustermanagementtoolkit.objgetters import objgetter_allowlist
from clustermanagementtoolkit import formatters
from clustermanagementtoolkit.formatters import formatter_allowlist
from clustermanagementtoolkit.ansible_helper import ansible_configuration
from clustermanagementtoolkit.ansible_helper import ansible_get_inventory_dict
from clustermanagementtoolkit.ansible_helper import ansible_get_groups, ansible_get_groups_by_host
from clustermanagementtoolkit.ansible_helper import ansible_add_hosts, ansible_remove_hosts
from clustermanagementtoolkit.ansible_helper import ansible_set_vars
from clustermanagementtoolkit.ansible_helper import ansible_run_playbook_on_selection
from clustermanagementtoolkit.ansible_helper import ansible_delete_log
from clustermanagementtoolkit.ansible_helper import ansible_print_play_results, get_playbook_path
from clustermanagementtoolkit.ansible_helper import ANSIBLE_INVENTORY
from clustermanagementtoolkit import helptexts
from clustermanagementtoolkit.kubernetes_helper import KubernetesHelper, KubernetesResourceCache
from clustermanagementtoolkit.kubernetes_helper import get_controller_from_owner_references
from clustermanagementtoolkit.kubernetes_helper import kubectl_get_version
from clustermanagementtoolkit.kubernetes_helper import update_api_status as kh_update_api_status
from clustermanagementtoolkit.kubernetes_helper import guess_kind
from clustermanagementtoolkit import checks
from clustermanagementtoolkit.ansithemeprint import ANSIThemeStr, ansithemestr_join_list
from clustermanagementtoolkit.ansithemeprint import clear_screen, ansithemeinput, ansithemeprint
from clustermanagementtoolkit import reexecutor
from clustermanagementtoolkit import about
PROGRAMDESCRIPTION = "UI for managing Kubernetes clusters"
PROGRAMAUTHORS = "Written by David Weinehall."
# If the user passes an object (and optionally namespace for that object)
# on the command line, they are stored here
# For pods a container can be appended too
initial_name = None # pylint: disable=invalid-name
initial_namespace = None # pylint: disable=invalid-name
initial_container = None # pylint: disable=invalid-name
# Is cmu running in read only-mode?
read_only_mode = False # pylint: disable=invalid-name
# Is Kubernetes support enabled
kubernetes_support = True # pylint: disable=invalid-name
kube_config_file = None # pylint: disable=invalid-name
# Namespace
selected_namespace = "" # pylint: disable=invalid-name
# defaults
defaultview = "" # pylint: disable=invalid-name
kh: KubernetesHelper = None # type: ignore
kh_cache: KubernetesResourceCache = None # type: ignore
executor = reexecutor.ReExecutor()
async_data: dict = {}
override_tail_lines = None # pylint: disable=invalid-name
DEFAULT_TAIL_LINES = 4000
force_refresh_apis = False # pylint: disable=invalid-name
views: dict[str, dict[str, Any]] = {}
infoviews: dict[tuple[str, str], Any] = {}
def init_kubernetes_client() -> None:
"""
Initialise the Kubernetes client.
"""
global kh # pylint: disable=global-statement
global kh_cache # pylint: disable=global-statement
if kubernetes_support:
kh = KubernetesHelper(about.PROGRAM_SUITE_NAME, about.PROGRAM_SUITE_VERSION,
config_path=kube_config_file)
kh_cache = KubernetesResourceCache()
# pylint: disable-next=too-many-locals
def gather_cluster_info(**kwargs: Any) -> None:
"""
Gather information about the cluster necessary for running playbooks.
Parameters:
**kwargs (dict[str, Any]): Keyword arguments
kubernetes_helper (KubernetesHelper): A reference to a KubernetesHelper object
"""
if (kh_ := deep_get(kwargs, DictPath("kubernetes_helper"))) is None:
raise ProgrammingError("gather_cluster_info() called without kubernetes_helper")
# Set global variables that need to be available when executing playbooks
join_token = kh_.get_join_token()
ca_cert_hash = kh_.get_ca_cert_hash()
control_plane_ip, control_plane_port, control_plane_path = kh_.get_control_plane_address()
_control_plane_node, control_plane_name = get_control_plane()
# This is tricky: we get this from the distro packages;
# since we cannot assume that we are running cmu on the [main] control plane
# we have to ask the [main] control plane, via ansible, what version of kubeadm it is running
package_versions = get_package_versions(control_plane_name)
control_plane_k8s_version = ""
for package, version in package_versions:
if package == "kubeadm":
control_plane_k8s_version = version
if not control_plane_k8s_version:
sys.exit(f"Failed to get kubeadm version from control plane “{control_plane_name}“; "
"aborting.")
http_proxy = deep_get(cmtlib.cmtconfig, DictPath("Network#http_proxy"), None)
https_proxy = deep_get(cmtlib.cmtconfig, DictPath("Network#https_proxy"), None)
no_proxy = deep_get(cmtlib.cmtconfig, DictPath("Network#no_proxy"), None)
insecure_registries = deep_get(cmtlib.cmtconfig, DictPath("Docker#insecure_registries"), [])
registry_mirrors = deep_get(cmtlib.cmtconfig, DictPath("Containerd#registry_mirrors"), [])
packages = deep_get(cmtlib.cmtconfig, DictPath("Packages"), {})
values = {
"control_plane_ip": control_plane_ip,
"control_plane_port": control_plane_port,
"control_plane_path": control_plane_path,
"join_token": join_token,
"ca_cert_hash": ca_cert_hash,
"control_plane_k8s_version": control_plane_k8s_version,
"ntp_server": control_plane_ip,
"http_proxy": http_proxy,
"https_proxy": https_proxy,
"no_proxy": no_proxy,
"insecure_registries": insecure_registries,
"registry_mirrors": registry_mirrors,
"packages": packages,
}
ansible_set_vars(ANSIBLE_INVENTORY, "all", values)
def format_timestamp(timestamp: datetime,
localtimezone: bool = False) -> list[Union[ThemeRef, ThemeStr]]:
"""
Takes datetime and formats it as a YYYY-MM-DD HH:MM:SS themearray.
Parameters:
timestamp (datetime): The timestamp
localtimezone (bool): Is the timestamp in local time?
Returns:
([ThemeRef|ThemeStr]): A formatted timestamp
"""
array = []
if timestamp is None:
array = [ThemeRef("strings", "none")]
else:
if localtimezone:
ftimestamp = f"{timestamp.astimezone():%Y-%m-%d %H:%M:%S}"
else:
ftimestamp = f"{timestamp:%Y-%m-%d %H:%M:%S}"
array = generators.format_numerical_with_units(ftimestamp, "timestamp", False)
return array
# pylint: disable-next=too-many-locals
def update_field_widths(field_dict: dict, field_names: list[str], objects: list[Type]) -> int:
"""
Process the fields for a line; calcute how wide each field should be,
then return the total line length.
Parameters:
field_dict (dict): The dict containing the description of the field
field_names ([str]): The names of the fields to populate
objects ([InfoClass]): An InfoClass object with the data
for all fields in the field_names list
Returns:
(int): The total length of all the fields of a line
"""
linelen: int = 0
pos: int = 0
for field_name in field_names:
field_dict[field_name]["pos"] = pos
field_dict[field_name]["fieldlen"] = 0
# These are necessary to calculate width of list items
item_separator = \
field_dict[field_name].get("item_separator", ThemeRef("separators", "list"))
field_separators = \
field_dict[field_name].get("field_separators", [ThemeRef("separators", "field")])
ellipsise = field_dict[field_name].get("ellipsise", -1)
ellipsis = field_dict[field_name].get("ellipsis", ThemeRef("separators", "ellipsis"))
field_prefixes = field_dict[field_name].get("field_prefixes", [])
field_suffixes = field_dict[field_name].get("field_suffixes", [])
field_formatters = field_dict[field_name].get("field_formatters", [])
formatting = deep_get(field_dict, DictPath(f"{field_name}#formatting"), {})
tmplen = 0
for obj in objects:
generator = field_dict[field_name].get("generator")
processor = field_dict[field_name].get("processor")
if processor is None:
processor = default_processor.get(generator)
if processor is not None:
if processor in (generators.processor_list, generators.processor_list_with_status):
tmp = processor(obj, field_name,
item_separator=item_separator,
field_separators=field_separators,
ellipsise=ellipsise, ellipsis=ellipsis,
field_prefixes=field_prefixes,
field_suffixes=field_suffixes,
field_formatters=field_formatters)
# pylint: disable-next=comparison-with-callable
elif processor == generators.processor_timestamp_with_age:
tmp = processor(obj, field_name, formatting)
else:
tmp = processor(obj, field_name)
else:
tmp = getattr(obj, field_name)
tmplen = max(len(str(tmp)), field_dict[field_name].get("fieldlen", 0))
field_dict[field_name]["fieldlen"] = tmplen
field_dict[field_name]["fieldlen"] = max(tmplen, len(field_dict[field_name]["header"]))
linelen += field_dict[field_name].get("fieldlen") + len(ThemeRef("separators", "pad"))
pos = linelen
# The last element should not be padded
if linelen:
linelen -= len(ThemeRef("separators", "pad"))
return linelen
def get_image_tuple(image: str) -> tuple[str, str]:
"""
Given the name of a container, return the name and the version field.
Paramters:
image (str): The full container name
Returns:
(str, str):
(str): The container name
(str): The container version
"""
tmp: Optional[re.Match[str]] = re.match(r"^(.*):(.*)", image)
if tmp is not None:
image_name = f"{tmp[1]}"
image_version = f"{tmp[2]}"
else:
image_name = f"{image}"
image_version = "<undefined>"
return image_name, image_version
def get_name_by_kind_from_owner_references(owner_references: list[dict], kind: str) -> str:
"""
Given a kind, and a list of owner-reference dicts, return the name of the referenced object.
FIXME: This should probably be modified to match kind as a tuple rather than only str,
or possibly removed completely.
Parameters:
owner_references ([dict[str, Any]]): A list of OWR dicts.
kind (str): The kind to search for.
Returns:
(str): The name of the object.
"""
for owr in owner_references:
if deep_get(owr, DictPath("kind"), "") == kind:
name = deep_get(owr, DictPath("name"))
break
return name
def get_holder_kind_from_owner_references(owner_references: list[dict], holder_name: str) -> str:
"""
Given a holder-name, and a list of owner-reference dicts, return the kind matches the name.
FIXME: Multiple owner-references may match the name; this returns the first one.
It should also be modified to return a tuple rather than only str,
or possibly removed completely.
Parameters:
owner_references ([dict[str, Any]]): A list of OWR dicts.
name (str): The name to search for.
Returns:
(str): The kind of the object.
"""
holder_kind: str = ""
for owr in owner_references:
if deep_get(owr, DictPath("name")) == holder_name:
holder_kind = deep_get(owr, DictPath("kind"), "")
break
return holder_kind
def get_pod_log_by_name_namespace_container(name: str, namespace: str, container: str,
tail_lines: int = DEFAULT_TAIL_LINES) \
-> tuple[str, bool]:
"""
Given name, namespace, and container, returns pod logs.
FIXME: This should be moved to kubernetes_helper.py.
Parameters:
name (str): The name of the object to get logs for
namespace (str): The namespace of the object to get logs for
container (str): The container to get logs for
tail_lines (int): The maximum number of log lines to fetch
Returns:
((str, bool)):
(str): The raw log message (with embedded newlines)
(bool): True if everything went OK, False if there was an error
"""
internal_error: bool = False
rawmsg, status = \
kh.read_namespaced_pod_log(name, namespace, container=container, tail_lines=tail_lines)
if status == 200:
# Everything is successful
internal_error = False
elif status == 400:
# Not successful; error in rawmsg
rawmsg = f"{datetime.now(timezone.utc):%Y-%m-%d %H:%M:%S} CRITICAL: {rawmsg}"
internal_error = True
elif status == 500:
# Not successful; error in rawmsg
internal_error = True
else:
rawmsg = f"{datetime.now(timezone.utc):%Y-%m-%d %H:%M:%S} CRITICAL: Failed to fetch log " \
f"for pod (name: {name}, namespace: {namespace}, container: {container}); " \
f"Request Status: {status}"
internal_error = True
if rawmsg.startswith("unable to retrieve container logs for"):
rawmsg = f"{datetime.now(timezone.utc):%Y-%m-%d %H:%M:%S} CRITICAL: {rawmsg}"
internal_error = True
return rawmsg, internal_error
# To make the failure case easier, return both the ref and the name of the control plane
def get_control_plane() -> tuple[dict[str, Any], str]:
"""
Return the name and object reference to the control plane.
FIXME: This does not support multiple control planes.
Returns:
((dict[str, Any], str)):
(dict[str, Any]): The object reference of the control plane
(str): The name of the control plane
"""
if not kubernetes_support:
return {}, ""
vlist, status = kh.get_list_by_kind_namespace(("Node", ""), "", resource_cache=kh_cache)
control_planes = []
if vlist is None or not vlist or status != 200:
return {}, ""
# Find control planes; but for now only return the first match
for obj in vlist:
labels = deep_get(obj, DictPath("metadata#labels"), {})
if "node-role.kubernetes.io/control-plane" in labels \
or "node-role.kubernetes.io/master" in labels:
control_planes.append((obj, deep_get(obj, DictPath("metadata#name"))))
# If we have exactly one node, assume that it is the control plane even if it lacks that label
if not control_planes and len(vlist) == 1:
control_planes.append((vlist[0], deep_get(vlist[0], DictPath("metadata#name"))))
if not control_planes:
ansithemeprint([ANSIThemeStr("Error", "warning"),
ANSIThemeStr(": None of the nodes in the cluster are labelled as "
"control planes. The cluster is most likely "
"misconfigured.", "default")], stderr=True)
return {}, ""
if len(control_planes) > 1:
ansithemeprint([ANSIThemeStr("Warning", "warning"),
ANSIThemeStr(": Multiple control planes not supported yet, "
"found multiple; returning first entry:", "default")],
stderr=True)
for control_plane in control_planes:
ansithemeprint([ANSIThemeStr(f" {control_plane[1]}", "default")], stderr=True)
return control_planes[0][0], control_planes[0][1]
# pylint: disable-next=unused-argument
def set_cluster_context(stdscr: curses.window, **kwargs: Any) -> Retval:
"""
Set Kubernetes cluster context.
Parameters:
stdscr (curses.window): The curses window to operate on
**kwargs (dict[str, Any]): Keyword arguments
selected (dict): The selected obj from a listpad
Returns:
(Retval): The return value
"""
global force_refresh_apis # pylint: disable=global-statement
selected: Type = deep_get(kwargs, DictPath("selected"))
name: str = getattr(selected, "name")
# If we actually changed context we need to force an API reload,
# since we might have changed between different clusters
# (or switched to a role that does not have access to a particular API).
if kh.set_context(name=name):
force_refresh_apis = True
return Retval.RETURNDONE
# pylint: disable-next=too-many-locals
def generate_list_header(uip: UIProps, field_dict: dict, is_taggable: bool = False) -> None:
"""
Generate the header for the listpad.
Parameters:
uip (UIProps): A reference to the UI Properties object
field_dict (dict): The dict containing the description of the field
is_taggable (bool): Is the list taggable?
"""
headerarray: list[Union[ThemeRef, ThemeStr]] = []
first = True
tabstops = []
tabstop = 0
# Is the list taggable?
if is_taggable:
tabstops.append(tabstop)
headerarray.append(ThemeRef("separators", "tag"))
tabstop = themearray_len(headerarray)
for field in field_dict:
generator = field_dict[field].get("generator")
if generator is None:
continue
tabstops.append(tabstop)
theme = get_theme_ref()
if uip.get_sortcolumn() == field:
if not uip.reversible:
sort_direction_char = theme["boxdrawing"]["arrownone"]
elif uip.sortorder_reverse:
sort_direction_char = theme["boxdrawing"]["arrowup"]
else:
sort_direction_char = theme["boxdrawing"]["arrowdown"]
else:
sort_direction_char = theme["boxdrawing"]["arrownone"]
# We always want this much padding between the headers,
# except if this is the first header
#
# Note that we need to subtract the width of sort direction char
# from the width of pad; this only works if len(pad) > 0
if not first:
separator_len = len(ThemeRef("separators", "pad"))
direction_char_len = len(sort_direction_char)
headerarray.append(ThemeStr("".ljust(separator_len - direction_char_len),
ThemeAttr("types", "generic")))
tabstop = themearray_len(headerarray)
# This tells the length of the alignment of the header
fieldlen = deep_get(field_dict, DictPath(f"{field}#fieldlen"))
header = deep_get(field_dict, DictPath(f"{field}#header"))
ralign = deep_get(field_dict, DictPath(f"{field}#ralign"), False)
# We cannot use ljust/rjust on the string,
# because we want the string and arrow in different colours,
# so just prepend/append whitespace instead
if ralign:
headerarray.append(ThemeStr("".ljust(fieldlen - len(header)),
ThemeAttr("types", "generic")))
headerarray.append(ThemeStr(header, ThemeAttr("main", "listheader"),
selected=uip.get_sortcolumn() == field))
headerarray.append(ThemeStr(sort_direction_char,
ThemeAttr("main", "listheader_arrows")))
if not ralign:
headerarray.append(ThemeStr("".ljust(fieldlen - len(header)),
ThemeAttr("types", "generic")))
first = False
# We've got to account for the last entry
if field_dict:
tabstops.append(tabstop)
# We've processed all fields, time to output the header
uip.addthemearray(uip.headerpad, headerarray, y=0, x=0)
uip.tabstops = tabstops
# pylint: disable-next=too-many-arguments,too-many-locals,too-many-positional-arguments
def generate_list_row(uip: UIProps, data: Type, field_dict: dict,
ypos: int, is_selected: bool, is_taggable: bool = False,
is_tagged: bool = False, is_deleted: bool = False) -> None:
"""
Generate a list for the listpad.
Parameters:
uip (UIProps): A reference to the UI Properties object
data (Type): The data to generate a list row from
field_dict (dict[str, Any]): The dict containing the description of the field
ypos (int): The list index
is_selected (bool): Is the list item selected?
is_taggable (bool): Is the list taggable?
is_tagged (bool): Is the list item tagged?
is_deleted (bool): Is the list item deleted?
"""
first: bool = True
i: int = 0
for field in field_dict:
i += 1
if is_taggable:
tagprefixlen = len(ThemeRef("separators", "tag"))
if is_tagged:
tagprefix: list[Union[ThemeRef, ThemeStr]] = [ThemeRef("separators", "tag")]
else:
tagprefix = [ThemeStr("".ljust(tagprefixlen), ThemeAttr("types", "generic"))]
else:
tagprefix = []
tagprefixlen = 0
generator = field_dict[field].get("generator")
if generator is None:
continue
if isinstance(generator, str):
generator = \
deep_get(generator_allowlist, DictPath(generator), generators.generator_basic)
fieldlen = field_dict[field]["fieldlen"]
if i < len(field_dict):
fpad = len(ThemeRef("separators", "pad"))
else:
fpad = 0
ralign = field_dict[field].get("ralign", False)
formatting = {
"item_separator":
field_dict[field].get("item_separator", ThemeRef("separators", "list")),
"field_separators":
field_dict[field].get("field_separators", [ThemeRef("separators", "field")]),
"field_colors": field_dict[field].get("field_colors", [ThemeAttr("types", "field")]),
"ellipsise": field_dict[field].get("ellipsise", -1),
"ellipsis": field_dict[field].get("ellipsis", ThemeRef("separators", "ellipsis")),
"field_prefixes": field_dict[field].get("field_prefixes", []),
"field_suffixes": field_dict[field].get("field_suffixes", []),
"mapping": field_dict[field].get("mapping", {}),
"field_formatters": field_dict[field].get("field_formatters", []),
}
tmp = generator(data, field, fieldlen, fpad, ralign, is_selected, **formatting)
pos = field_dict[field]["pos"]
if first and is_taggable:
uip.addthemearray(uip.listpad, tagprefix, y=ypos, x=pos, deleted=is_deleted)
first = False
uip.addthemearray(uip.listpad, tmp, y=ypos, x=pos + tagprefixlen, deleted=is_deleted)
# noqa: E501 pylint: disable-next=too-many-locals,too-many-branches,too-many-statements,too-many-return-statements
def genericlistloop(stdscr: curses.window, **kwargs: Any) -> Retval:
"""
Generic main loop for listviews.
Parameters:
stdscr (curses.window): The curses window to operate on
**kwargs (dict[str, Any]): Keyword arguments
view (str): The view to show
Returns:
(Retval): The return value
Raises:
ProgrammingError (view is invalid)
"""
global executor # pylint: disable=global-statement
global selected_namespace # pylint: disable=global-statement
global initial_name # pylint: disable=global-statement
global initial_namespace # pylint: disable=global-statement
# Just in case there are leftover futures from other views
executor.shutdown()
executor = reexecutor.ReExecutor()
view = deep_get(kwargs, DictPath("kind"))
viewref = deep_get(views, DictPath(view), {})
kind = deep_get(viewref, DictPath("kind"))
if not (isinstance(stdscr, curses.window) and isinstance(view, str)):
msg = [
[("genericlistloop()", "emphasis"),
(" called with invalid argument(s):", "error")],
[("stdscr = ", "default"),
(f"{stdscr}", "argument"),
(" (type: ", "default"),
(f"{type(stdscr)}", "argument"),
(", expected: ", "default"),
("{curses.window}", "argument"),
(")", "default")],
[("view = ", "default"),
(f"{yaml.dump(view)}", "argument"),
(" (type: ", "default"),
(f"{type(view)}", "argument"),
(", expected: ", "default"),
("str", "argument"),
(")", "default")],
]
unformatted_msg, formatted_msg = ANSIThemeStr.format_error_msg(msg)
raise ProgrammingError(unformatted_msg,
severity=LogLevel.ERR,
formatted_msg=formatted_msg)
denylist = deep_get(viewref, DictPath("field_denylist"), [])
field_indexes = deep_get(viewref, DictPath("field_indexes"), {})
if not (isinstance(field_indexes, dict) and field_indexes):
msg = [
[("genericlistloop()", "emphasis"),
(" called with invalid argument(s):", "error")],
[("field_indexes = ", "default")],
[(f"{yaml.dump(field_indexes)}", "argument"),
(" (type: ", "default"),
(f"{type(field_indexes)}", "argument"),
(", expected: ", "default"),
(f"{dict}", "argument"),
(") with at least one element", "default")],
]
unformatted_msg, formatted_msg = ANSIThemeStr.format_error_msg(msg)
raise ProgrammingError(unformatted_msg,
severity=LogLevel.ERR,
formatted_msg=formatted_msg)
if "Custom" in field_indexes:
field_index = "Custom"
elif "Wide" in field_indexes:
field_index = "Wide"
else:
field_index = list(field_indexes.keys())[0]
fieldgenerator_args = {
"field_index": field_index,
"field_indexes": field_indexes,
"fields": deep_get(viewref, DictPath("fields")),
"denylist": denylist,
}
field_dict, field_names, sortcolumn, sortorder_reverse = \
generators.fieldgenerator(view=view, selected_namespace=selected_namespace,
**fieldgenerator_args)
uip = UIProps(stdscr)
windowheader = view
if kind is None or kind[0].startswith("__"):
is_namespaced = False
else:
is_namespaced = kh.is_kind_namespaced(kind)
helptext = generate_helptext(view, "listview", [], {})
activatedfun = deep_get(viewref, DictPath("activatedfun"), genericinfoloop)
on_activation = deep_get(viewref, DictPath("on_activation"), {})
update_delay = deep_get(viewref, DictPath("update_delay"), -1)
is_taggable = (deep_get(viewref, DictPath("is_taggable"), True)
and deep_get(viewref, DictPath("actions")) is not None)
extra_vars = deep_get(viewref, DictPath("extra_vars"), {})
uip.init_window(field_dict=field_dict, view=kind, windowheader=windowheader,
update_delay=update_delay, sortcolumn=sortcolumn,
sortorder_reverse=sortorder_reverse, helptext=helptext,
activatedfun=activatedfun, on_activation=on_activation)
# The statusbar is always located at the bottom of the screen and fills the entire width
uip.init_statusbar()
# For the list
uip.init_listpad(listheight=1, width=-1, ypos=1, xpos=1)
label_selector = ""
# These values can be toggled, so we need to read them first
listview_args = copy.deepcopy(deep_get(viewref, DictPath("listview_args"), {}))
listgetter = deep_get(viewref, DictPath("listgetter"))
listgetter_async = deep_get(viewref, DictPath("listgetter_async"))
listgetter_args = deep_get(viewref, DictPath("listgetter_args"), {})
listgetter_args["label_selector"] = label_selector
infogetter = deep_get(viewref, DictPath("infogetter"), infogetters.generic_infogetter)
infogetter_extra_args = deep_get(viewref, DictPath("extra_vars#infogetter"),
{"_view": view.strip("*")})
infogetter_extra_args["_field_index"] = field_index.lower()
infogetter_extra_args["_field_names"] = field_names
infogetter_extra_args["_field_dict"] = field_dict
if "filters" in listview_args:
infogetter_extra_args["_filters"] = deep_get(listview_args, DictPath("filters"))
uip.last_action = datetime.now()
uip.idle_timeout = 5
tagged_items: set[Type] = set()
serverstatus: str = "ok"
first_fetch: bool = True
new_data: str = "false"
uip.force_update()
uip.listlen = 0
# pylint: disable-next=too-many-nested-blocks
while True:
if listgetter_async is not None:
# Temporary workaround
# pylint: disable-next=comparison-with-callable
if listgetter_async == listgetters_async.get_inventory_list and "hosts" not in executor:
hosts = list(deep_get(ansible_get_inventory_dict(), DictPath("all#hosts")).keys())
# The inventory doesn't change all that often,
# but reading it every 10 seconds should be OK
executor.trigger("hosts", 10, read_file_async, path=ANSIBLE_INVENTORY,
filetype="yaml", **listgetter_args)
async_data["hosts"] = copy.deepcopy(hosts)
infogetter_extra_args["_match_key"] = "name"
new_data = "pending"
first_fetch = False
# pylint: disable-next=comparison-with-callable
elif listgetter_async == listgetters_async.get_context_list \
and (first_fetch or uip.update_forced):
vlist, hosts = listgetters_async.get_context_list(kubernetes_helper=kh)
async_data["hosts"] = copy.deepcopy(hosts)
infogetter_extra_args["_vlist"] = copy.deepcopy(vlist)
infogetter_extra_args["_match_key"] = "server_address"
new_data = "pending"
first_fetch = False
# pylint: disable-next=comparison-with-callable
elif listgetter_async == listgetters_async.get_kubernetes_list \
and ".".join(kind) not in executor:
if "kubernetes_helper" not in listgetter_args:
listgetter_args["kubernetes_helper"] = kh
listgetter_args["kh_cache"] = kh_cache
if "kind" not in listgetter_args:
listgetter_args["kind"] = kind
if "namespace" not in listgetter_args:
listgetter_args["namespace"] = selected_namespace
executor.trigger(".".join(kind), 5, listgetters_async.get_kubernetes_list,
**listgetter_args)
if listgetter_async in (listgetters_async.get_inventory_list,
listgetters_async.get_context_list) and "pings" not in executor:
facts_ping_playbook_path = get_playbook_path(FilePath("facts_ping.yaml"))
# But the hosts can change status more frequently than that
executor.trigger("pings", 5, run_ansible_play_async,
playbook=facts_ping_playbook_path, selection=hosts, verbose=False)
elif listgetter is not None:
if first_fetch or uip.update_forced:
if listgetter is not None:
if "kubernetes_helper" not in listgetter_args:
listgetter_args["kubernetes_helper"] = kh
listgetter_args["kh_cache"] = kh_cache
if kind[0].startswith("__"):
vlist, status = listgetter(**listgetter_args)
else:
raise ProgrammingError("We don't know how to handle this")
# else:
# vlist, status = \
# listgetter(deep_get(view, DictPath(f"{view}#kind")),
# selected_namespace,
# label_selector=label_selector, **listgetter_args)
infogetter_extra_args["_vlist"] = vlist
new_data = "pending"
uip.update_timestamp(update=new_data)
first_fetch = False
else:
# We only have an infogetter
new_data = "pending"
uip.update_timestamp(update=new_data)
first_fetch = False
# The asynchronous UI follows these rules:
# Idle:
# No user activity within the last idle_timeout seconds
# Force refresh:
# User pressed [F5], changed sort column,
# or opened/closed a dialog ([F1], [F2], [F8], etc)
# Additional blockers:
# Items are tagged, menus are open, etc.
if executor:
if (execution_result_dict := executor.get("hosts")) != ([], []):
data, _host_statuses = execution_result_dict
hosts = deep_get(cast(dict, data), DictPath("all#hosts"), {}).keys()
hosts_set = set(hosts)
async_data["hosts"] = list(hosts)
if vlist := deep_get(infogetter_extra_args, DictPath("_vlist"), []):
vlist_hosts = [deep_get(item, DictPath("name")) for item in vlist]
vlist_hosts_set = set(vlist_hosts)
else:
vlist_hosts = []
vlist_hosts_set = set()
# Only add hosts that aren't part of vlist already
inventory_dict = ansible_get_inventory_dict()
for host in hosts_set - vlist_hosts_set:
vlist.append({
"name": host,
"ref": host,
"ips": [],
"ansible_groups": ansible_get_groups_by_host(inventory_dict, host),
"status": "UNKNOWN",
"__deleted": False,
})
# Tag hosts in vlist that are no longer part of hosts as deleted
for host in vlist_hosts_set - hosts_set:
for i, item in enumerate(vlist):
if deep_get(item, DictPath("name"), "") == host:
vlist[i]["status"] = "DELETED"
vlist[i]["__deleted"] = True
infogetter_extra_args["_vlist"] = copy.deepcopy(vlist)
if not uip.listlen:
uip.force_update()
new_data = "pending"
uip.update_timestamp(update=new_data)
first_fetch = False
elif (execution_result_dict := executor.get("pings")) != ([], []):
ansible_results, _ansible_status = execution_result_dict
vlist = deep_get(infogetter_extra_args, DictPath("_vlist"), [])
for i, item in enumerate(vlist):
host = deep_get(item, DictPath(infogetter_extra_args["_match_key"]))
for result in deep_get(cast(dict[str, Any], ansible_results),
DictPath(f"{host}"), []):
if deep_get(result, DictPath("task")) == "Ping":
if not deep_get(vlist[i], DictPath("__deleted"), False):
status = deep_get(result, DictPath("status"))
vlist[i]["status"] = status
ips = []
if (ip := deep_get(result,
DictPath("ansible_facts#"
"ansible_default_ipv4#address"), "")):
ips.append(ip)
if (ip := deep_get(result,
DictPath("ansible_facts#"
"ansible_default_ipv6#address"), "")):
ips.append(ip)
vlist[i]["ips"] = copy.deepcopy(ips)
_pings_args, pings_kwargs = executor.get_parameters("pings")
if set(async_data["hosts"]) != set(deep_get(pings_kwargs,
DictPath("selection"), [])):
executor.update("pings", selection=copy.deepcopy(async_data["hosts"]))
executor.retrigger("pings")
infogetter_extra_args["_vlist"] = copy.deepcopy(vlist)
if not uip.listlen:
uip.force_update()
new_data = "pending"