-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcmt
executable file
·3954 lines (3563 loc) · 168 KB
/
cmt
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
#
# Copyright the Cluster Management Toolkit for Kubernetes contributors.
# SPDX-License-Identifier: MIT
# 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 errno
from getpass import getuser
import hashlib
from operator import itemgetter
import os
from pathlib import Path
import re
import sys
from typing import Any, cast, Optional
from collections.abc import Sequence
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.")
from cryptography import x509
from cryptography.hazmat.primitives import serialization
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.cluster_actions import get_crio_version
from clustermanagementtoolkit.cmttypes import deep_get, DictPath, SecurityStatus
from clustermanagementtoolkit.cmttypes import FilePath, FilePathAuditError, HostNameStatus
from clustermanagementtoolkit.cmtpaths import CMT_CONFIG_FILE, CMT_CONFIG_FILENAME
from clustermanagementtoolkit.cmtpaths import DEFAULT_THEME_FILE, VIEW_DIR, SYSTEM_VIEWS_DIR
from clustermanagementtoolkit.cmtvalidators import validate_fqdn, validator_bool
from clustermanagementtoolkit.commandparser import parse_commandline, CommandType
from clustermanagementtoolkit.ansible_helper import ansible_configuration, get_playbook_path
from clustermanagementtoolkit.ansible_helper import ansible_run_playbook_on_selection
from clustermanagementtoolkit.ansible_helper import ansible_get_hosts_by_group, ansible_add_hosts
from clustermanagementtoolkit.ansible_helper import ansible_remove_hosts
from clustermanagementtoolkit.ansible_helper import ansible_print_action_summary
from clustermanagementtoolkit.ansible_helper import ansible_print_play_results
from clustermanagementtoolkit.ansible_helper import populate_playbooks_from_filenames
from clustermanagementtoolkit.ansible_helper import ANSIBLE_INVENTORY
from clustermanagementtoolkit import cmtlib
from clustermanagementtoolkit.cmtlib import chunk_list, identify_distro, read_cmtconfig
from clustermanagementtoolkit.cmtlib import get_cluster_name, get_latest_upstream_version
from clustermanagementtoolkit import cmtio
from clustermanagementtoolkit.cmtio import execute_command, secure_read_string
from clustermanagementtoolkit.cmtio_yaml import secure_read_yaml
from clustermanagementtoolkit.networkio import scan_and_add_ssh_keys
from clustermanagementtoolkit import kubernetes_helper
from clustermanagementtoolkit.kubernetes_helper import list_contexts, get_node_roles
from clustermanagementtoolkit.kubernetes_helper import get_node_status, kubectl_get_version
from clustermanagementtoolkit.kubernetes_helper import update_api_status as kh_update_api_status
from clustermanagementtoolkit.kubernetes_helper import set_context, guess_kind
from clustermanagementtoolkit import checks
from clustermanagementtoolkit.ansithemeprint import ANSIThemeStr, ansithemestr_join_list
from clustermanagementtoolkit.ansithemeprint import ansithemeprint, ansithemeinput
from clustermanagementtoolkit.ansithemeprint import ansithemeinput_password
from clustermanagementtoolkit import about
PROGRAMDESCRIPTION = "Commandline tool for managing Kubernetes clusters"
PROGRAMAUTHORS = "Written by David Weinehall."
kh: kubernetes_helper.KubernetesHelper = None # type: ignore
def request_ansible_password() -> None:
"""
Requests the ansible password.
"""
# Check whether ansible_password is defined or not
if ansible_configuration["ansible_password"] is None:
ansithemeprint([ANSIThemeStr("Attention", "warning"),
ANSIThemeStr(": To be able to run playbooks you need to provide the "
"ansible/ssh password.", "default")])
ansithemeprint([ANSIThemeStr("Since the systems will be reconfigured to use passwordless "
"sudo and ssh keys this is a one-time thing.", "default")])
ansible_password = ansithemeinput_password([ANSIThemeStr("\nPassword: ", "default")])
if ansible_password is None or not ansible_password:
ansithemeprint([ANSIThemeStr("\nError", "error"),
ANSIThemeStr(": Empty password; aborting.", "default")], stderr=True)
sys.exit(errno.EINVAL)
ansible_configuration["ansible_password"] = ansible_password
# pylint: disable-next=too-many-locals
def run_playbook(playbookpath: FilePath, hosts: list[str], extra_values: Optional[dict] = None,
quiet: bool = False, verbose: bool = False) -> tuple[int, dict]:
"""
Run an Ansible playbook.
Parameters:
playbookpath (FilePath): A path to the playbook to run
hosts ([str]): A list of hosts to run the playbook on
extra_values (dict): A dict of values to set before running the playbook
quiet (bool): Should the results of the run be printed? (Unused)
verbose (bool): If the results are printed, should skipped tasks be printed too?
Returns:
(int): The return value from ansible_run_playbook_on_selection()
(dict): A dict with the results from the run
"""
# The first patch revision that isn't available from the new repositories is 1.24.0,
# but anything older than 1.28.0 is signed with a key that has expired, so only
# include 1.28.0 and newer; the old repository is no longer usable.
if (kubernetes_upstream_version := get_latest_upstream_version("kubernetes")) is None:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": Could not get the latest upstream Kubernetes version; ",
"default"),
ANSIThemeStr("this is either a network error or a bug; aborting.",
"default")], stderr=True)
sys.exit(errno.ENOENT)
# Split the version tuple
_upstream_major, upstream_minor, _rest = kubernetes_upstream_version.split(".")
minor_versions = []
for minor_version in range(28, int(upstream_minor) + 1):
minor_versions.append(f"{minor_version}")
# Set necessary Ansible keys before running playbooks
http_proxy = deep_get(cmtlib.cmtconfig, DictPath("Network#http_proxy"), "")
if http_proxy is None:
http_proxy = ""
https_proxy = deep_get(cmtlib.cmtconfig, DictPath("Network#https_proxy"), "")
if https_proxy is None:
https_proxy = ""
no_proxy = deep_get(cmtlib.cmtconfig, DictPath("Network#no_proxy"), "")
if no_proxy is None:
no_proxy = ""
insecure_registries = deep_get(cmtlib.cmtconfig, DictPath("Docker#insecure_registries"), [])
registry_mirrors = deep_get(cmtlib.cmtconfig, DictPath("Containerd#registry_mirrors"), [])
retval = 0
use_proxy = "no"
if http_proxy or https_proxy:
use_proxy = "yes"
if extra_values is None:
extra_values = {}
values = {
"http_proxy": http_proxy,
"https_proxy": https_proxy,
"no_proxy": no_proxy,
"insecure_registries": insecure_registries,
"registry_mirrors": registry_mirrors,
"use_proxy": use_proxy,
"minor_versions": minor_versions,
}
merged_values = {**values, **extra_values}
retval, ansible_results = \
ansible_run_playbook_on_selection(playbookpath, selection=hosts,
values=merged_values, quiet=False)
if retval == -errno.ENOENT and not ansible_results:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default"),
ANSIThemeStr(f"{ANSIBLE_INVENTORY}", "path"),
ANSIThemeStr(" is either empty or missing; aborting.", "default")],
stderr=True)
sys.exit(errno.ENOENT)
if not quiet:
ansible_print_play_results(retval, ansible_results, verbose=verbose)
print()
return retval, ansible_results
def __format_none(string: Optional[str], fmt: str) -> ANSIThemeStr:
if string is None or string == "<none>":
__string = ANSIThemeStr("<none>", "none")
else:
__string = ANSIThemeStr(string, fmt)
return __string
def get_control_planes() -> list[tuple[str, list[str]]]:
"""
Get the list of control planes.
Returns:
[(str, [str])]: The list of control planes
(str): The name of the control plane
([str]): A list of IP-addresses for the control plane
"""
global kh # pylint: disable=global-statement
controlplanes = []
if kh is None:
kh = kubernetes_helper.KubernetesHelper(about.PROGRAM_SUITE_NAME,
about.PROGRAM_SUITE_VERSION, None)
vlist, status = kh.get_list_by_kind_namespace(("Node", ""), "")
if status != 200:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": API-server returned ", "default"),
ANSIThemeStr(f"{status}", "errorvalue"),
ANSIThemeStr("; aborting.", "default")], stderr=True)
sys.exit(errno.EINVAL)
if vlist is None:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": API-server did not return any data", "default")],
stderr=True)
sys.exit(errno.EINVAL)
for node in vlist:
name = deep_get(node, DictPath("metadata#name"))
node_roles = get_node_roles(cast(dict, node))
if "control-plane" in node_roles or "master" in node_roles:
ipaddresses = []
for address in deep_get(node, DictPath("status#addresses")):
if deep_get(address, DictPath("type"), "") == "InternalIP":
ipaddresses.append(deep_get(address, DictPath("address")))
controlplanes.append((name, ipaddresses))
return controlplanes
def show_configuration(hosts: list[str], cri: Optional[str] = None) -> None:
"""
Show cluster configuration.
Parameters:
hosts ([str]): The hosts that will be affected
"""
cluster_name = get_cluster_name()
controlplanes = get_control_planes()
http_proxy = deep_get(cmtlib.cmtconfig, DictPath("Network#http_proxy"), "")
if http_proxy is not None and http_proxy == "":
http_proxy = None
http_proxy_env = os.getenv("http_proxy")
if http_proxy_env is not None and http_proxy_env == "":
http_proxy_env = None
https_proxy = deep_get(cmtlib.cmtconfig, DictPath("Network#https_proxy"), "")
if https_proxy is not None and https_proxy == "":
https_proxy = None
https_proxy_env = os.getenv("https_proxy")
if https_proxy_env is not None and https_proxy_env == "":
https_proxy_env = None
no_proxy = deep_get(cmtlib.cmtconfig, DictPath("Network#no_proxy"), "")
if no_proxy is not None and no_proxy == "":
no_proxy = None
no_proxy_env = os.getenv("no_proxy")
if no_proxy_env is not None and no_proxy_env == "":
no_proxy_env = None
ansithemeprint([ANSIThemeStr("\n[Summary]", "phase")])
ansithemeprint([ANSIThemeStr("\n• ", "separator"),
ANSIThemeStr("Configuration:", "action")])
ansithemeprint([ANSIThemeStr(" Cluster Name: ", "action"),
ANSIThemeStr(f"{cluster_name}", "hostname")])
if cri is not None:
ansithemeprint([ANSIThemeStr(" CRI: ", "action"),
ANSIThemeStr(f"{cri}", "programname")])
ansithemeprint([ANSIThemeStr(" HTTP Proxy: ", "action"),
__format_none(http_proxy, "url"),
ANSIThemeStr(" (", "default"),
ANSIThemeStr(f"{CMT_CONFIG_FILE}", "path"),
ANSIThemeStr(")", "default")])
ansithemeprint([ANSIThemeStr(" HTTP Proxy: ", "action"),
__format_none(http_proxy_env, "url"),
ANSIThemeStr(" (Environment)", "default")])
ansithemeprint([ANSIThemeStr(" HTTPS Proxy: ", "action"),
__format_none(https_proxy, "url"),
ANSIThemeStr(" (", "default"),
ANSIThemeStr(f"{CMT_CONFIG_FILE}", "path"),
ANSIThemeStr(")", "default")])
ansithemeprint([ANSIThemeStr(" HTTPS Proxy: ", "action"),
__format_none(https_proxy_env, "url"),
ANSIThemeStr(" (Environment)", "default")])
ansithemeprint([ANSIThemeStr(" No Proxy: ", "action"),
__format_none(no_proxy, "url"),
ANSIThemeStr(" (", "default"),
ANSIThemeStr(f"{CMT_CONFIG_FILE}", "path"),
ANSIThemeStr(")", "default")])
ansithemeprint([ANSIThemeStr(" No Proxy: ", "action"),
__format_none(no_proxy_env, "url"),
ANSIThemeStr(" (Environment)", "default")])
ansithemeprint([ANSIThemeStr("", "default")])
ansithemeprint([ANSIThemeStr("• ", "separator"),
ANSIThemeStr("Control Planes:", "action")])
for controlplane in controlplanes:
ansithemeprint([ANSIThemeStr(" • ", "separator"),
ANSIThemeStr(f"{controlplane[0]} ", "emphasis"),
ANSIThemeStr("(", "default")]
+ ansithemestr_join_list(controlplane[1], formatting="hostname",
separator=ANSIThemeStr(",", "separator"))
+ [ANSIThemeStr(")", "default")])
ansithemeprint([ANSIThemeStr("\n• ", "separator"),
ANSIThemeStr("Target Hosts:", "action")])
for host in hosts:
ansithemeprint([ANSIThemeStr(" • ", "separator"),
ANSIThemeStr(host, "hostname")])
def run_playbooks(playbooks: list[tuple[list[ANSIThemeStr], FilePath]], **kwargs: Any) -> bool:
"""
Run a set of Ansible playbooks.
Parameters:
playbooks ([([ANSIThemeStr], FilePath)]): A list of playbooks
**kwargs (dict[str, Any]): Keyword arguments
hosts (str): The hosts to run the playbooks on
extra_values (dict): Variables to set before running the playbooks
verbose (bool): If the results are printed, should skipped tasks be printed too?
Returns:
(bool): True on success, False on failure
"""
hosts: Optional[list[str]] = deep_get(kwargs, DictPath("hosts"))
extra_values: Optional[dict] = deep_get(kwargs, DictPath("extra_values"))
verbose: bool = deep_get(kwargs, DictPath("verbose"), False)
if not playbooks or hosts is None:
return True
for string, playbookpath in playbooks:
ansithemeprint(string)
retval, _ansible_results = \
run_playbook(playbookpath, hosts=hosts,
extra_values=extra_values, verbose=verbose)
# We do not want to continue executing playbooks if the first one failed
if retval != 0:
break
return retval == 0
# pylint: disable-next=too-many-branches
def get_selection(selection: list[str],
kind: Optional[tuple[str, str]] = None) -> tuple[list[str], list[str], list[str]]:
"""
Based on input parameters, split the node list into nodes,
non-existing nodes, and control planes.
Parameters:
selection ([str]): A list of nodes, or ALL to select all nodes
kind ((str, str)): A Kubernetes kind; only supported for now is ("Node", "")
Returns:
([str], [str], [str]):
([str]): The nodes
([str]): The non-existing nodes
([str]): The control planes
"""
global kh # pylint: disable=global-statement
all_items = False
items1 = []
non_existing = []
# Only used for controlplanes
items2 = []
if kind is None:
raise ValueError("kind is None; this is a programming error")
if selection is None:
raise ValueError("selection is None; this is a programming error")
if "ALL" in selection:
if len(selection) > 1:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": “", "default"),
ANSIThemeStr("ALL", "argument"),
ANSIThemeStr("“ cannot be combined with other arguments; "
"aborting.", "default")], stderr=True)
sys.exit(errno.EINVAL)
else:
all_items = True
# Kubernetes resources
if isinstance(kind, tuple):
if kh is None:
kh = kubernetes_helper.KubernetesHelper(about.PROGRAM_SUITE_NAME,
about.PROGRAM_SUITE_VERSION, None)
vlist, status = kh.get_list_by_kind_namespace(("Node", ""), "")
if status != 200:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": API-server returned ", "default"),
ANSIThemeStr(f"{status}", "errorvalue"),
ANSIThemeStr("; aborting.", "default")], stderr=True)
sys.exit(errno.EINVAL)
if vlist is None:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": API-server did not return any data", "default")],
stderr=True)
sys.exit(errno.EINVAL)
for node in vlist:
name = deep_get(node, DictPath("metadata#name"))
if not all_items and name not in selection:
continue
node_roles = get_node_roles(cast(dict, node))
if "control-plane" in node_roles or "master" in node_roles:
items2.append(name)
continue
items1.append(name)
# str kinds are things such as playbooks; for now cmt does not use them
# Finally, generate a list of non-existing items
if not all_items:
for item in selection:
if item not in items1 + items2:
non_existing.append(item)
return items1, non_existing, items2
# pylint: disable-next=too-many-branches
def cordon_nodes(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Cordon nodes.
Parameters:
options ([(str, str)]): Options to use when executing this action
args ([str]): Arguments to use when executing this action
Returns:
(int): 0 on success, exits with errno on failure
"""
global kh # pylint: disable=global-statement
include_control_planes = False
header = True
for opt, _optarg in options:
if opt == "--include-control-planes":
include_control_planes = True
elif opt == "--no-header":
header = False
selection = args[0].split(",")
# It is OK to specify control planes individually
if "ALL" not in selection:
include_control_planes = True
_nodes, non_existing, controlplanes = get_selection(args[0].split(","), kind=("Node", ""))
nodes = []
nodes += _nodes
if include_control_planes:
nodes += controlplanes
if non_existing:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default")]
+ ansithemestr_join_list(non_existing, formatting="hostname",
separator=ANSIThemeStr(",", "separator"))
+ [ANSIThemeStr(" are not part of the cluster; aborting.", "default")],
stderr=True)
sys.exit(errno.ENOENT)
if not nodes:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": No nodes available; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
if header:
ansithemeprint([ANSIThemeStr("\n[Cordoning nodes]", "phase")])
if kh is None:
kh = kubernetes_helper.KubernetesHelper(about.PROGRAM_SUITE_NAME,
about.PROGRAM_SUITE_VERSION, None)
for node in nodes:
ansithemeprint([ANSIThemeStr(f"{node}:", "hostname")])
message, status = kh.cordon_node(node)
if status in (200, 204):
ansithemeprint([ANSIThemeStr(" Cordoned", "success")])
print(message)
elif status == 42503:
ansithemeprint([ANSIThemeStr("", "default")])
ansithemeprint([ANSIThemeStr("Critical", "critical"),
ANSIThemeStr(": Cluster not available; aborting", "default")],
stderr=True)
sys.exit(errno.ENOENT)
else:
ansithemeprint([ANSIThemeStr("\nAPI call returned error:", "error")], stderr=True)
ansithemeprint([ANSIThemeStr(f" {message}", "error")], stderr=True)
sys.exit(errno.EINVAL)
return 0
# pylint: disable-next=too-many-branches,too-many-locals
def drain_nodes(options: Sequence[tuple[str, Optional[str]]], args: list[str]) -> int:
"""
Drain nodes.
Parameters:
options ([(str, str)]): Options to use when executing this action
args ([str]): Arguments to use when executing this action
Returns:
(int): 0 on success, exits with errno on failure
"""
include_control_planes = False
header = True
# Check kubectl version
kubectl_major_version, kubectl_minor_version, _kubectl_git_version, \
_server_major_version, _server_minor_version, _server_git_version = kubectl_get_version()
if kubectl_major_version is None or kubectl_minor_version is None:
ansithemeprint([ANSIThemeStr("Critical", "critical"),
ANSIThemeStr(": Could not extract ", "default"),
ANSIThemeStr("kubectl", "programname"),
ANSIThemeStr(" version; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
_args = ["/usr/bin/kubectl", "drain"]
for opt, _optarg in options:
if opt in ("--delete-emptydir-data", "--delete-local-data"):
if kubectl_major_version >= 1 and kubectl_minor_version >= 20:
_args.append("--delete-emptydir-data")
else:
_args.append("--delete-local-data")
elif opt == "--disable-eviction":
if kubectl_major_version >= 1 and kubectl_minor_version >= 18:
_args.append(opt)
elif opt == "--ignore-daemonsets":
_args.append(opt)
elif opt == "--include-control-planes":
include_control_planes = True
elif opt == "--no-header":
header = False
selection = args[0].split(",")
# It is OK to specify control planes individually
if "ALL" not in selection:
include_control_planes = True
_nodes, non_existing, controlplanes = get_selection(args[0].split(","), kind=("Node", ""))
nodes = []
nodes += _nodes
if include_control_planes:
nodes += controlplanes
if non_existing:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default")]
+ ansithemestr_join_list(non_existing, formatting="hostname",
separator=ANSIThemeStr(",", "separator"))
+ [ANSIThemeStr(" are not part of the cluster; aborting.", "default")],
stderr=True)
sys.exit(errno.ENOENT)
if not nodes:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": No nodes available; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
if header:
ansithemeprint([ANSIThemeStr("\n[Draining nodes]", "phase")])
_args += nodes
execute_command(_args)
return 0
# pylint: disable-next=too-many-branches
def uncordon_nodes(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Uncordon nodes.
Parameters:
options ([(str, str)]): Options to use when executing this action
args ([str]): Arguments to use when executing this action
Returns:
(int): 0 on success, exits with errno on failure
"""
global kh # pylint: disable=global-statement
include_control_planes = False
header = True
for opt, _optarg in options:
if opt == "--include-control-planes":
include_control_planes = True
elif opt == "--no-header":
header = False
selection = args[0].split(",")
# It is OK to specify control planes individually
if "ALL" not in selection:
include_control_planes = True
_nodes, non_existing, controlplanes = get_selection(args[0].split(","), kind=("Node", ""))
nodes = []
nodes += _nodes
if include_control_planes:
nodes += controlplanes
if non_existing:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default")]
+ ansithemestr_join_list(non_existing, formatting="hostname",
separator=ANSIThemeStr(",", "separator"))
+ [ANSIThemeStr(" are not part of the cluster; aborting.", "default")],
stderr=True)
sys.exit(errno.ENOENT)
if not nodes:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": No nodes available; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
if header:
ansithemeprint([ANSIThemeStr("\n[Uncordoning nodes]", "phase")])
if kh is None:
kh = kubernetes_helper.KubernetesHelper(about.PROGRAM_SUITE_NAME,
about.PROGRAM_SUITE_VERSION, None)
for node in nodes:
ansithemeprint([ANSIThemeStr(f"{node}:", "hostname")])
message, status = kh.uncordon_node(node)
if status in (200, 204):
ansithemeprint([ANSIThemeStr(" Uncordoned", "success")])
print(message)
elif status == 42503:
ansithemeprint([ANSIThemeStr("", "default")])
ansithemeprint([ANSIThemeStr("Critical", "critical"),
ANSIThemeStr(": Cluster not available; aborting", "default")],
stderr=True)
sys.exit(errno.ENOENT)
else:
ansithemeprint([ANSIThemeStr("\nAPI call returned error:", "error")], stderr=True)
ansithemeprint([ANSIThemeStr(f" {message}", "error")], stderr=True)
sys.exit(errno.EINVAL)
return 0
# pylint: disable-next=too-many-statements,too-many-branches,too-many-locals
def taint_nodes(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Taint nodes.
Parameters:
options ([(str, str)]): Options to use when executing this action
args ([str]): Arguments to use when executing this action
Returns:
(int): 0 on success, exits with errno on failure
"""
global kh # pylint: disable=global-statement
include_control_planes = False
overwrite = False
header = True
for opt, _optarg in options:
if opt == "--include-control-planes":
include_control_planes = True
elif opt == "--no-header":
header = False
elif opt == "--overwrite":
overwrite = True
selection = args[0].split(",")
taint = args[1]
if ":" in taint:
taint_key_value, taint_new_effect = taint.split(":")
else:
taint_key_value = taint
taint_new_effect = None
if "=" in taint_key_value:
taint_key, taint_value = taint_key_value.split("=")
else:
taint_key = taint_key_value
taint_value = None
# It is OK to specify control planes individually
if "ALL" not in selection:
include_control_planes = True
_nodes, non_existing, controlplanes = get_selection(args[0].split(","), kind=("Node", ""))
nodes = []
nodes += _nodes
if include_control_planes:
nodes += controlplanes
if non_existing:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default")]
+ ansithemestr_join_list(non_existing, formatting="hostname",
separator=ANSIThemeStr(",", "separator"))
+ [ANSIThemeStr(" are not part of the cluster; aborting.", "default")],
stderr=True)
sys.exit(errno.ENOENT)
if not nodes:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": No nodes available; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
if header:
ansithemeprint([ANSIThemeStr("\n[Tainting nodes]", "phase")])
if kh is None:
kh = kubernetes_helper.KubernetesHelper(about.PROGRAM_SUITE_NAME,
about.PROGRAM_SUITE_VERSION, None)
for node in nodes:
node_info = kh.get_ref_by_kind_name_namespace(("Node", ""), node, "")
if node is None:
continue
node_status, _status_group, _taints, full_taints = \
get_node_status(cast(dict[str, Any], node_info))
if node_status == "Unknown":
ansithemeprint([ANSIThemeStr("Critical", "critical"),
ANSIThemeStr(": Failed to get node information; do you have a "
"running cluster? Aborting.", "default")], stderr=True)
sys.exit(errno.ENXIO)
ansithemeprint([ANSIThemeStr(node, "hostname")])
_message, status = \
kh.taint_node(node, full_taints,
(taint_key, taint_value, None, taint_new_effect), overwrite=overwrite)
if status == 304:
ansithemeprint([ANSIThemeStr(" Not modified", "none")])
elif status == 42304:
ansithemeprint([ANSIThemeStr(" Warning", "warning"),
ANSIThemeStr(": Ignoring request; node already has taint(s) with "
"matching effect; use “", "default"),
ANSIThemeStr("--overwrite", "option"),
ANSIThemeStr("“ to override", "default")])
elif status == 200:
ansithemeprint([ANSIThemeStr(" Tainted", "success")])
else:
ansithemeprint([ANSIThemeStr(" Failed to modify taint", "error"),
ANSIThemeStr(f"; HTTP error {status}; aborting.", "default")],
stderr=True)
sys.exit(errno.EINVAL)
return 0
# pylint: disable-next=too-many-statements,too-many-branches,too-many-locals
def untaint_nodes(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Untaint nodes.
Parameters:
options ([(str, str)]): Options to use when executing this action
args ([str]): Arguments to use when executing this action
Returns:
(int): 0 on success, exits with errno on failure
"""
global kh # pylint: disable=global-statement
include_control_planes = False
header = True
for opt, _optarg in options:
if opt == "--include-control-planes":
include_control_planes = True
elif opt == "--no-header":
header = False
selection = args[0].split(",")
taint = args[1]
if ":" in taint:
taint_key_value, taint_old_effect = taint.split(":")
else:
taint_key_value = taint
taint_old_effect = None
if "=" in taint_key_value:
taint_key, taint_value = taint.split("=")
else:
taint_key = taint
taint_value = None
# It is OK to specify control planes individually
if "ALL" not in selection:
include_control_planes = True
_nodes, non_existing, controlplanes = get_selection(args[0].split(","), kind=("Node", ""))
nodes = []
nodes += _nodes
if include_control_planes:
nodes += controlplanes
if non_existing:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default")]
+ ansithemestr_join_list(non_existing, formatting="hostname",
separator=ANSIThemeStr(",", "separator"))
+ [ANSIThemeStr(" are not part of the cluster; aborting.", "default")],
stderr=True)
sys.exit(errno.ENOENT)
if not nodes:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": No nodes available; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
if header:
ansithemeprint([ANSIThemeStr("\n[Untainting nodes]", "phase")])
if kh is None:
kh = kubernetes_helper.KubernetesHelper(about.PROGRAM_SUITE_NAME,
about.PROGRAM_SUITE_VERSION, None)
for node in nodes:
if (node_info := kh.get_ref_by_kind_name_namespace(("Node", ""), node, "")) is None:
continue
node_status, _status_group, _taints, full_taints = get_node_status(node_info)
if node_status == "Unknown":
ansithemeprint([ANSIThemeStr("Critical", "critical"),
ANSIThemeStr(": Failed to get node information; do you have a "
"running cluster? Aborting.", "default")], stderr=True)
sys.exit(errno.ENXIO)
ansithemeprint([ANSIThemeStr(node, "hostname")])
_message, status = kh.taint_node(node, full_taints,
(taint_key, taint_value, taint_old_effect, None))
if status == 304:
ansithemeprint([ANSIThemeStr(" Not modified", "none")])
elif status == 200:
ansithemeprint([ANSIThemeStr(" Untainted", "success")])
else:
ansithemeprint([ANSIThemeStr(" Failed to modify taint", "error"),
ANSIThemeStr(f"; HTTP error {status}; aborting.", "default")],
stderr=True)
sys.exit(errno.EINVAL)
return 0
# pylint: disable-next=too-many-statements,too-many-branches,too-many-locals
def prepare_hosts(options: list[tuple[str, str]], args: list[str]) -> int:
"""
Install and configure pre-requisites for use as a node.
Parameters:
options ([(str, str)]): Options to use when executing this action
args ([str]): Arguments to use when executing this action
Returns:
(int): 0 on success, exits with errno on failure
"""
ignore_existing = False
no_password = False
from_file = False
confirm = True
verbose = False
for opt, optarg in options:
if opt == "--ignore-existing":
ignore_existing = True
elif opt == "--no-password":
no_password = True
elif opt == "--save-ansible-logs":
ansible_configuration["save_logs"] = True
elif opt == "--forks":
ansible_configuration["ansible_forks"] = optarg
elif opt == "--from-file":
from_file = True
elif opt == "--verbose":
verbose = True
elif opt == "-Y":
confirm = False
if from_file:
hostfile = args[0]
hostfile_path = Path(hostfile)
if not hostfile_path.exists():
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default"),
ANSIThemeStr(f"{hostfile}", "path"),
ANSIThemeStr(" does not exist; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
if not hostfile_path.is_file():
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default"),
ANSIThemeStr(f"{hostfile}", "path"),
ANSIThemeStr(" is not a file; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
hosts_raw = secure_read_string(FilePath(hostfile))
hosts_raw_split = hosts_raw.splitlines()
if len(hosts_raw_split) == 1 and "," in hosts_raw_split[0]:
selection = hosts_raw_split[0].split(",")
else:
selection = hosts_raw_split
else:
selection = args[0].split(",")
if "ALL" in selection:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default"),
ANSIThemeStr("ALL", "hostname"),
ANSIThemeStr(" cannot be used with ", "default"),
ANSIThemeStr("prepare", "command"),
ANSIThemeStr("; aborting.", "default")], stderr=True)
sys.exit(errno.EINVAL)
# Validate FQDN/hostname list
for hostname in selection:
if validate_fqdn(hostname, message_on_error=True) != HostNameStatus.OK:
sys.exit(errno.EINVAL)
# Correlate the list of hosts with the nodes in the cluster
nodes, non_existing, controlplanes = get_selection(selection, kind=("Node", ""))
if nodes or controlplanes:
if not ignore_existing:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": ", "default")]
+ ansithemestr_join_list(nodes + controlplanes, formatting="hostname",
separator=ANSIThemeStr(",", "separator"))
+ [ANSIThemeStr(" are already part of the cluster; aborting.",
"default")], stderr=True)
sys.exit(errno.EEXIST)
else:
ansithemeprint([ANSIThemeStr("Warning", "warning"),
ANSIThemeStr(": ", "default")]
+ ansithemestr_join_list(nodes + controlplanes, formatting="hostname",
separator=ANSIThemeStr(",", "separator"))
+ [ANSIThemeStr(" are already part of the cluster; "
"ignoring them since “", "description"),
ANSIThemeStr("--ignore-existing", "option"),
ANSIThemeStr("“ was specified.", "default")])
if not non_existing:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": No valid hosts specified; aborting.", "default")],
stderr=True)
sys.exit(errno.ENOENT)
# Check if the hosts are part of the inventory
inventory = ansible_get_hosts_by_group(ANSIBLE_INVENTORY, "all")
not_in_inventory = []
for host in non_existing:
if host not in inventory:
not_in_inventory.append(host)
if not_in_inventory:
if confirm:
input_retval = \
ansithemeinput([ANSIThemeStr("\nWarning", "warning"),
ANSIThemeStr(": ", "default")]
+ ansithemestr_join_list(not_in_inventory, formatting="hostname",
separator=ANSIThemeStr(",", "separator"))
+ [ANSIThemeStr(" are not defined in the inventory; do you want to "
"add them now? (No will abort the installation) "
"[y/", "default"),
ANSIThemeStr("N", "emphasis"), ANSIThemeStr("]: ", "default")])
if input_retval.lower() not in ("y", "yes"):
ansithemeprint([ANSIThemeStr("\nAborting", "error"),
ANSIThemeStr(": Nodes not added to the inventory.", "default")],
stderr=True)
sys.exit(errno.EINTR)
else:
ansithemeprint([ANSIThemeStr("\nNote", "note"),
ANSIThemeStr(": ", "default")]
+ ansithemestr_join_list(not_in_inventory, formatting="hostname",
separator=ANSIThemeStr(",", "separator"))