-
Notifications
You must be signed in to change notification settings - Fork 3
/
cmtadm
executable file
·7956 lines (7048 loc) · 355 KB
/
cmtadm
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: python3 (>= 3.9)
# Requires: python3-natsort
# Requires: python3-paramiko
#
# Copyright the Cluster Management Toolkit for Kubernetes contributors.
# SPDX-License-Identifier: MIT
# pylint: disable=too-many-lines
import errno
from getpass import getuser
from glob import glob
import grp
import os
from pathlib import Path
import pwd
import re
import shutil
import socket
from subprocess import CalledProcessError # nosec
import sys
import tempfile
from typing import Any, cast, Optional, Union
from collections.abc import Callable
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 create_vm_hosts, join_nodes, get_crio_version
from clustermanagementtoolkit.cluster_actions import prepare_nodes, prepare_vm_template
from clustermanagementtoolkit.cmttypes import deep_get, DictPath, FilePath, FilePathAuditError
from clustermanagementtoolkit.cmttypes import SecurityChecks, SecurityPolicy, SecurityStatus
from clustermanagementtoolkit.cmtpaths import BASH_COMPLETION_BASE_DIR, BASH_COMPLETION_DIR
from clustermanagementtoolkit.cmtpaths import BINDIR, HOMEDIR
from clustermanagementtoolkit.cmtpaths import SSH_DIR, SSH_KEYGEN_BIN_PATH, SSH_KEYGEN_ARGS
from clustermanagementtoolkit.cmtpaths import DEPLOYMENT_DIR
from clustermanagementtoolkit.cmtpaths import CMT_PRE_PREPARE_DIR, CMT_POST_PREPARE_DIR
from clustermanagementtoolkit.cmtpaths import CMT_PRE_SETUP_DIR, CMT_POST_SETUP_DIR
from clustermanagementtoolkit.cmtpaths import CMT_PRE_UPGRADE_DIR, CMT_POST_UPGRADE_DIR
from clustermanagementtoolkit.cmtpaths import CMT_PRE_TEARDOWN_DIR, CMT_POST_TEARDOWN_DIR
from clustermanagementtoolkit.cmtpaths import CMT_PRE_PURGE_DIR, CMT_POST_PURGE_DIR
from clustermanagementtoolkit.cmtpaths import ANSIBLE_INVENTORY
from clustermanagementtoolkit.cmtpaths import DEFAULT_THEME_FILE
from clustermanagementtoolkit.cmtpaths import CMT_CONFIG_FILE, CMT_INSTALLATION_INFO_FILE
from clustermanagementtoolkit.cmtpaths import KUBE_CONFIG_DIR, KUBE_CONFIG_FILE
from clustermanagementtoolkit.commandparser import parse_commandline
from clustermanagementtoolkit.ansible_helper import ansible_configuration
from clustermanagementtoolkit.ansible_helper import ansible_get_inventory_dict, ansible_set_vars
from clustermanagementtoolkit.ansible_helper import ansible_run_playbook_on_selection
from clustermanagementtoolkit.ansible_helper import ansible_add_hosts
from clustermanagementtoolkit.ansible_helper import ansible_get_hosts_by_group, get_playbook_path
from clustermanagementtoolkit.ansible_helper import ansible_print_play_results
from clustermanagementtoolkit.ansible_helper import populate_playbooks_from_filenames
from clustermanagementtoolkit import cmtio
from clustermanagementtoolkit.cmtio import check_path
from clustermanagementtoolkit.cmtio import execute_command, execute_command_with_response
from clustermanagementtoolkit.cmtio import secure_mkdir, secure_read_string, secure_rm
from clustermanagementtoolkit.cmtio import secure_which, secure_write_string
from clustermanagementtoolkit.cmtio_yaml import secure_read_yaml, secure_write_yaml
from clustermanagementtoolkit.networkio import download_files
from clustermanagementtoolkit.networkio import scan_and_add_ssh_keys, update_version_cache
from clustermanagementtoolkit import cmtlib
from clustermanagementtoolkit.cmtlib import check_versions_apt
from clustermanagementtoolkit.cmtlib import check_versions_yum, check_versions_zypper
from clustermanagementtoolkit.cmtlib import get_latest_upstream_version, get_cluster_name
from clustermanagementtoolkit.cmtlib import identify_distro, read_cmtconfig
from clustermanagementtoolkit.cmtlib import substitute_list, substitute_string
from clustermanagementtoolkit.cni_data import cni_data
from clustermanagementtoolkit import kubernetes_helper
from clustermanagementtoolkit.kubernetes_helper import get_node_roles
from clustermanagementtoolkit.ansithemeprint import ANSIThemeStr, ansithemeinput
from clustermanagementtoolkit.ansithemeprint import ansithemeinput_password, ansithemeprint
from clustermanagementtoolkit.ansithemeprint import ansithemestr_join_list
from clustermanagementtoolkit.ansithemeprint import themearray_override_formatting
from clustermanagementtoolkit import fieldgetters
from clustermanagementtoolkit import checks
from clustermanagementtoolkit import about
PROGRAMDESCRIPTION = "Setup or teardown a Kubernetes cluster"
PROGRAMAUTHORS = "Written by David Weinehall."
DEFAULT_CNI = "cilium"
DEFAULT_POD_NETWORK_CIDR = "10.244.0.0/16"
no_password = False # pylint: disable=invalid-name
kh: kubernetes_helper.KubernetesHelper = None # type: ignore
cri_data: dict = {
"containerd": {
"socket": "unix:///run/containerd/containerd.sock",
},
"cri-o": {
"socket": "unix:///run/crio/crio.sock",
},
}
prepare_targets: dict = {
"kubeadm": {
"pretty_name": [("kubeadm", "programname"), (" (default)", "default")],
"playbooks": [
FilePath("prepare_passwordless_ansible.yaml"),
FilePath("install_packages.yaml"),
FilePath("prepare_control_plane.yaml"),
FilePath("add_kubernetes_repo.yaml"),
],
"deb_packages": [
],
"fedora_packages": [
],
"suse_packages": [
],
},
"localhost": {
"pretty_name": [("host system", "programname")],
"playbooks": [
FilePath("prepare_passwordless_ansible.yaml"),
FilePath("add_kubernetes_repo.yaml"),
FilePath("install_packages.yaml"),
],
"deb_packages": [
"ansible",
],
"fedora_packages": [
"ansible-core",
],
"suse_packages": [
"ansible",
],
},
"rke2": {
"pretty_name": [("kubeadm", "programname"), (" (default)", "default")],
"playbooks": [
FilePath("prepare_passwordless_ansible.yaml"),
FilePath("install_packages.yaml"),
FilePath("prepare_control_plane.yaml"),
],
"deb_packages": [
],
"fedora_packages": [
],
"suse_packages": [
],
},
}
setup_control_plane_targets: dict = {
"kubeadm": {
"pretty_name": [("kubeadm", "programname"), (" (default)", "default")],
"playbooks": [
FilePath("install_packages.yaml"),
FilePath("kubeadm_setup_control_plane.yaml"),
FilePath("fetch_kube_config.yaml"),
],
"deb_packages": [
"kubeadm",
"kubectl",
"kubelet",
"kubernetes-cni",
],
"deb_packages_held": [
"kubeadm",
"kubectl",
"kubelet",
],
"fedora_packages": [
"kubeadm",
"kubectl",
"kubelet",
],
"fedora_packages_held": [
"kubeadm",
"kubectl",
"kubelet",
],
"suse_packages": [
"kubectl",
# "kubernetes{major.minor}-client",
"kubeadm",
# "kubernetes{major.minor}-kubeadm",
"kubelet",
# "kubernetes{major.minor}-kubelet",
],
"suse_packages_held": [
"kubectl",
# "kubernetes{major.minor}-client",
"kubeadm",
# "kubernetes{major.minor}-kubeadm",
"kubelet",
# "kubernetes{major.minor}-kubelet",
],
"extra_values": {},
},
"localhost": {
"pretty_name": [("host system", "programname")],
"playbooks": [
FilePath("install_packages.yaml"),
],
"deb_packages": [
"kubectl",
],
"deb_packages_held": [
"kubectl",
],
"fedora_packages": [
"kubectl",
],
"fedora_packages_held": [
"kubectl",
],
"suse_packages": [
"kubectl",
# "kubernetes{major.minor}-client",
],
"suse_packages_held": [
"kubectl",
# "kubernetes{major.minor}-client",
],
},
"rke2": {
"pretty_name": [("RKE2", "programname")],
"playbooks": [
FilePath("rke2_setup_control_plane.yaml"),
FilePath("fetch_kube_config.yaml"),
],
"extra_values": {},
},
}
upgrade_control_plane_targets: dict = {
"kubeadm": {
"pretty_name": [("kubeadm", "programname"), (" (default)", "default")],
"playbooks": [
FilePath("kubeadm_upgrade_control_plane.yaml"),
],
"extra_values": {},
},
"localhost": {
"pretty_name": [("host system", "programname")],
"playbooks": [
FilePath("install_packages.yaml"),
],
"deb_packages": [
"kubectl",
],
"deb_packages_held": [
"kubectl",
],
"fedora_packages": [
"kubectl",
],
"fedora_packages_held": [
"kubectl",
],
},
"rke2": {
"pretty_name": [("RKE2", "programname")],
"playbooks": [
FilePath("rke2_upgrade_control_plane.yaml"),
],
"extra_values": {},
},
}
teardown_control_plane_targets: dict = {
"kubeadm": {
"pretty_name": [("kubeadm", "programname"), (" (default)", "default")],
"playbooks": [
FilePath("teardown_cni.yaml"),
FilePath("kubeadm_teardown_control_plane.yaml"),
],
},
"rke2": {
"pretty_name": [("RKE2", "programname")],
"playbooks": [
FilePath("rke2_teardown_control_plane.yaml"),
],
},
}
purge_control_plane_targets: dict = {
"kubeadm": {
"pretty_name": [("kubeadm", "programname"), (" (default)", "default")],
"playbooks": [
FilePath("kubeadm_purge.yaml"),
],
"deb_packages": [
"kubeadm",
"kubectl",
"kubelet",
"kubernetes-cni",
],
"deb_packages_held": [
"kubeadm",
"kubectl",
"kubelet",
],
"fedora_packages": [
"kubeadm",
"kubectl",
"kubelet",
"kubernetes-cni",
],
"fedora_packages_held": [
"kubeadm",
"kubectl",
"kubelet",
],
},
"rke2": {
"pretty_name": [("rke2", "programname")],
"playbooks": [
FilePath("rke2_purge.yaml"),
],
},
}
# pylint: disable-next=too-many-locals,too-many-branches
def get_control_plane_version(controlplane: str, k8s_distro: str) -> str:
"""
Return the Kubernetes version used by the control plane.
Parameters:
controlplane (str): Name of the node to check the version from
k8s_distro (str): The Kubernetes distro used
Returns:
(str): The Kubernetes version if discernible, the empty string if not
"""
global kh # pylint: disable=global-statement
version = None
if k8s_distro == "rke2":
# This will only work for running clusters
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 name == controlplane:
version = deep_get(node, DictPath("status#nodeInfo#kubeletVersion"))
break
else:
# For kubeadm we try to use the package version
get_versions_path = get_playbook_path(FilePath("get_versions.yaml"))
retval, ansible_results = \
ansible_run_playbook_on_selection(get_versions_path,
selection=[controlplane], quiet=False)
if not ansible_results:
raise ValueError(f"Error: Failed to get package versions from {controlplane} "
f"(retval: {retval}); aborting.")
k8s_distro = "<unknown>"
version = "<unknown>"
for result in deep_get(ansible_results, DictPath(controlplane), []):
if deep_get(result, DictPath("task"), "") == "Package versions":
tmp = deep_get(result, DictPath("msg_lines"), [])
break
if len(tmp) == 0:
raise ValueError(f"Error: Received empty version data from {controlplane} "
f"(retval: {retval}); aborting.")
package_version_regex: re.Pattern[str] = re.compile(r"^(.*?): (.*)")
for line in tmp:
tmp2 = package_version_regex.match(line)
if tmp2 is None:
continue
package = tmp2[1]
package_version = tmp2[2]
if package == "kubeadm":
version = package_version
break
if version is None:
version = ""
return version
# pylint: disable-next=too-many-locals,too-many-branches,too-many-statements
def rebuild_installation_info(state: Optional[str] = None) -> None:
"""
If the installation info file does not exist, but a cluster already exists
and is part of the inventory, this function will try to rebuild the installation info file.
Parameters:
state (str): The installation state
"""
global kh # pylint: disable=global-statement
k8s_distro = None
controlplane = None
cri = "<none>"
# This will only work for running clusters
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:
controlplane = name
cri = deep_get(node, DictPath("status#nodeInfo#containerRuntimeVersion"), "")
if cri is not None:
cri = cri.split(":")[0]
tmp_k8s_distro = None
minikube_name = deep_get(node, DictPath("metadata#labels#minikube.k8s.io/name"), "")
labels = deep_get(node, DictPath("metadata#labels"), {})
images = deep_get(node, DictPath("status#images"), [])
for image in images:
names = deep_get(image, DictPath("names"), [])
for name in names:
if "openshift-crc-cluster" in name:
tmp_k8s_distro = "crc"
break
if tmp_k8s_distro is not None:
break
if minikube_name != "":
tmp_k8s_distro = "minikube"
elif deep_get(labels, DictPath("microk8s.io/cluster"), False):
tmp_k8s_distro = "microk8s"
elif deep_get(node, DictPath("spec#providerID"), "").startswith("kind://"):
tmp_k8s_distro = "kind"
else:
managed_fields = deep_get(node, DictPath("metadata#managedFields"), [])
for managed_field in managed_fields:
manager = deep_get(managed_field, DictPath("manager"), "")
if manager == "rke2":
tmp_k8s_distro = "rke2"
break
if manager == "k0s":
tmp_k8s_distro = "k0s"
break
if manager.startswith("deploy@k3d"):
tmp_k8s_distro = "k3d"
break
if manager == "k3s":
tmp_k8s_distro = "k3s"
break
if manager == "kubeadm":
tmp_k8s_distro = "kubeadm"
break
if tmp_k8s_distro is not None:
if k8s_distro is not None:
ansithemeprint([ANSIThemeStr("Critical", "critical"),
ANSIThemeStr(": The control planes are reporting conflicting "
"Kubernetes distros; aborting.",
"default")], stderr=True)
sys.exit(errno.EINVAL)
else:
k8s_distro = tmp_k8s_distro
if controlplane is None:
ansithemeprint([ANSIThemeStr("", "default")])
ansithemeprint([ANSIThemeStr("Critical", "critical"),
ANSIThemeStr(": Could not identify a control plane for the cluster; "
"aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
if k8s_distro is None:
ansithemeprint([ANSIThemeStr("Critical", "critical"),
ANSIThemeStr(": Unknown Kubernetes distro; cannot determine Kubernetes "
"version.", "default")], stderr=True)
sys.exit(errno.EINVAL)
version = get_control_plane_version(controlplane=controlplane, k8s_distro=k8s_distro)
if version is None or not version:
ansithemeprint([ANSIThemeStr("", "default")])
ansithemeprint([ANSIThemeStr("Critical", "critical"),
ANSIThemeStr(": Failed to get Kubernetes version; currently only kubeadm "
"and RKE2 are supported. Aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
cluster_name = get_cluster_name()
pod_network_cidr = kh.get_pod_network_cidr()
cnis = kh.identify_cni()
if len(cnis) == 1:
cni = cnis[0][0]
else:
cni = "<unknown>"
update_installation_info(installation_target=cluster_name, cluster_name=cluster_name,
distro=k8s_distro, version=version, requested_version="<none>",
state=state, phase="<none>", phase_skiplist=[], cni=cni, cri=cri,
pod_network_cidr=pod_network_cidr)
def get_installation_info(cluster_name: Optional[str] = None,
ignore_non_existing: bool = True) -> dict:
"""
Return installation info for a cluster, or prepares a new entry if no entry exists yet.
Parameters:
cluster_name (str): The name of the cluster to get information for
ignore_non_existing (bool): Ignore and recreate installation_info.yaml
if the file doesn't exist
Returns:
(dict): A dictionary with information about a cluster
"""
info = None
# We are OK with the file not existing
security_checks = [
SecurityChecks.PARENT_RESOLVES_TO_SELF,
SecurityChecks.OWNER_IN_ALLOWLIST,
SecurityChecks.PARENT_OWNER_IN_ALLOWLIST,
SecurityChecks.PERMISSIONS,
SecurityChecks.PARENT_PERMISSIONS,
SecurityChecks.IS_FILE,
]
try:
info = secure_read_yaml(CMT_INSTALLATION_INFO_FILE, checks=security_checks)
except FileNotFoundError:
if not ignore_non_existing:
ansithemeprint([ANSIThemeStr("Error", "error"),
ANSIThemeStr(": Could not open ", "default"),
ANSIThemeStr(f"{CMT_INSTALLATION_INFO_FILE}", "path"),
ANSIThemeStr("; aborting.", "default")], stderr=True)
sys.exit(errno.ENOENT)
if info is None or info.get("installation_target") is None \
or (info.get("installation_target") is not None
and cluster_name is not None and cluster_name not in info):
if info is None:
info = {}
info["installation_target"] = cluster_name
info[cluster_name] = {
"distro": "<none>",
"version": "<none>",
"requested_version": "<none>",
"state": "<none>",
"phase": "<none>",
"phase_skiplist": [],
"cni": "<none>",
"pod_network_cidr": "<none>",
"cri": "<none>",
}
elif info.get("installation_target") is None and cluster_name is not None:
# Old format file; transition it
tmpinfo = info.copy()
tmpinfo.pop("cluster_name")
info = {}
info["installation_target"] = cluster_name
info[cluster_name] = tmpinfo
return info
# pylint: disable-next=too-many-branches
def update_installation_info(**kwargs: Any) -> dict:
"""
Update installation info for a cluster.
Parameters:
**kwargs (dict[str, Any]): Keyword arguments
installation_target (str): The installation info entry to use
cluster_name (str): The name of the cluster to update information for
distro (str): The distribution used during installation
(currently the only supported distro is kubeadm)
version (str): The current version of Kubernetes
requested_version (str): The requested version of Kubernetes
state (str): The installation state
phase (str): The installation phase
phase_skiplist (list[str]): A list of phases to skip
cni (str): The CNI to use
pod_network_cidr (str): The CIDR to use for the pod network
cri (str): The CRI to use
control_planes ([str]): A list of the control planes
nodes ([str]): A list of the nodes
Returns:
(dict): The updated installation info
"""
installation_target: Optional[str] = deep_get(kwargs, DictPath("installation_target"))
cluster_name: Optional[str] = deep_get(kwargs, DictPath("cluster_name"))
distro: Optional[str] = deep_get(kwargs, DictPath("distro"))
version: Optional[str] = deep_get(kwargs, DictPath("version"))
requested_version: Optional[str] = deep_get(kwargs, DictPath("requested_version"))
state: Optional[str] = deep_get(kwargs, DictPath("state"))
phase: Optional[Union[int, str]] = deep_get(kwargs, DictPath("phase"))
phase_skiplist: Optional[list[str]] = deep_get(kwargs, DictPath("phase_skiplist"))
cni: Optional[str] = deep_get(kwargs, DictPath("cni"))
pod_network_cidr: Optional[str] = deep_get(kwargs, DictPath("pod_network_cidr"))
cri: Optional[str] = deep_get(kwargs, DictPath("cri"))
control_planes: Optional[list[str]] = deep_get(kwargs, DictPath("control_planes"))
nodes: Optional[list[str]] = deep_get(kwargs, DictPath("nodes"))
info = get_installation_info(cluster_name=cluster_name)
if cluster_name is None:
cluster_name = info.get("installation_target")
if installation_target is not None:
info["installation_target"] = installation_target
elif info.get("installation_target") is None:
info["installation_target"] = cluster_name
if distro is not None:
info[cluster_name]["distro"] = distro
if version is not None:
info[cluster_name]["version"] = version
if requested_version is not None:
info[cluster_name]["requested_version"] = requested_version
if state is not None:
info[cluster_name]["state"] = state
if phase is not None:
info[cluster_name]["phase"] = phase
if phase_skiplist is not None:
info[cluster_name]["phase_skiplist"] = phase_skiplist
if cni is not None:
info[cluster_name]["cni"] = cni
if pod_network_cidr is not None:
info[cluster_name]["pod_network_cidr"] = pod_network_cidr
if cri is not None:
info[cluster_name]["cri"] = cri
if control_planes is not None:
info[cluster_name]["control_planes"] = control_planes
if nodes is not None:
info[cluster_name]["nodes"] = nodes
secure_write_yaml(CMT_INSTALLATION_INFO_FILE, info, sort_keys=False)
return info
def check_and_print_status(retval: bool) -> None:
"""
A wrapper that prints OK if retval is True
and NOT OK and aborts if retval is False.
Parameters:
retval (bool): True on success, False on failure
"""
if retval:
ansithemeprint([ANSIThemeStr("OK", "ok")])
else:
ansithemeprint([ANSIThemeStr("NOT OK", "notok"),
ANSIThemeStr("; aborting.", "default")], stderr=True)
sys.exit(errno.EINVAL)
def check_version_from_url(url: str, version_regex: str) -> list[str]:
"""
Given a URL download a text file and treat the first line
that matches version_regex as a version number.
Parameters:
url (str): A URL
version_regex (str): A regex
Returns:
(str): The version number, or None in case of failure
"""
version: list[str] = []
if url is not None:
with tempfile.TemporaryDirectory() as td:
check_and_print_status(download_files(td, [(url, "version.txt", None, None)],
permissions=0o600))
tmp = secure_read_string(FilePath(f"{td}/version.txt"))
versionoutput = tmp.splitlines()
_version_regex: re.Pattern[str] = re.compile(version_regex)
for line in versionoutput:
tmp_match = _version_regex.match(line)
if tmp_match is not None:
version = list(tmp_match.groups())
break
return version
def check_version_from_executable(command: FilePath, args: list[str],
version_regex: str) -> list[str]:
"""
Given a path to an executable, the arguments needed to show version information,
and a version_regex, return the executable version.
Parameters:
command (str): A path to an executable
args ([str]): A list of arguments necessary to show version information
version_regex (str): A regex
Returns:
([str]): A list of version number elements, or None in case of failure
"""
version: list[str] = []
security_policy = SecurityPolicy.ALLOWLIST_RELAXED
fallback_allowlist = ["/bin", "/sbin", "/usr/bin", "/usr/sbin",
"/usr/local/bin", "/usr/local/sbin", f"{HOMEDIR}/bin"]
try:
cpath = cmtio.secure_which(command, fallback_allowlist=fallback_allowlist,
security_policy=security_policy)
except FileNotFoundError:
cpath = None
if cpath is not None:
result = execute_command_with_response([cpath] + args)
if result is not None:
versionoutput = result.splitlines()
_version_regex: re.Pattern[str] = re.compile(version_regex)
for line in versionoutput:
tmp = _version_regex.match(line)
if tmp is not None:
version = list(tmp.groups())
break
return version
# pylint: disable-next=too-many-locals,too-many-branches,too-many-statements
def __upgrade_cni(cni: str, upgradetype: str, context: str,
pod_network_cidr: str, **kwargs: Any) -> None:
"""
A helper that is used when upgrading a CNI;
it can either upgrade the CNI itself or a helper executable.
Parameters:
cni (str): The CNI to upgrade
upgradetype (str): Valid options CNI, executable
context (str): The cluster context
pod_network_cidr (str): The CIDR of the pod network
cni_version (str): A hardcoded CNI version
"""
verbose = deep_get(kwargs, DictPath("verbose"), False)
cni_version = deep_get(kwargs, DictPath("cni_version"))
if upgradetype not in ("CNI", "executable"):
raise ValueError(f"Unknown upgradetype {upgradetype}; this is a programming error.")
# FIXME: for now we hardcode this
arch = "amd64"
version_command = deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#version_command"))
version_command_regex = deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#version_regex"))
candidate_version_url = \
deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#candidate_version_url"))
candidate_version_command = \
deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#candidate_version_command"))
candidate_version_function = \
deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#candidate_version_function"))
manual_candidate_version_regex = \
deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#manual_candidate_version_regex"))
candidate_version_regex = \
deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#candidate_version_regex"))
install_command = deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#install"))
upgrade_command = deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#upgrade"))
version_substitutions = {
"<<<arch>>>": arch,
"<<<context>>>": context,
}
version = []
if version_command is not None:
ansithemeprint([ANSIThemeStr("\n• ", "separator"),
ANSIThemeStr(f"Checking {upgradetype} version", "action")])
version = \
check_version_from_executable(version_command[0],
substitute_list(version_command[1:],
version_substitutions),
version_command_regex)
candidate_version = []
if cni_version is not None:
if (tmp_candidate_version := re.match(manual_candidate_version_regex, cni_version)) is None:
check_and_print_status(False)
# The type ignore below is necessary because mypy doesn't recognise that
# check_and_print_status always aborts with sys.exit() when called with False
candidate_version = list(tmp_candidate_version.groups()) # type: ignore
elif candidate_version_url is not None:
ansithemeprint([ANSIThemeStr("\n• ", "separator"),
ANSIThemeStr(f"Checking {upgradetype} candidate version", "action")])
if candidate_version_function is not None:
tmp_candidate_version_fun = candidate_version_function(candidate_version_url,
candidate_version_regex)
if tmp_candidate_version_fun is None:
check_and_print_status(False)
candidate_version, _release_data, _body = tmp_candidate_version_fun
else:
candidate_version = \
check_version_from_url(substitute_string(candidate_version_url,
version_substitutions),
candidate_version_regex)
elif candidate_version_command is not None:
ansithemeprint([ANSIThemeStr("\n• ", "separator"),
ANSIThemeStr(f"Checking {upgradetype} candidate version", "action")])
candidate_version = \
check_version_from_executable(candidate_version_command[0],
substitute_list(candidate_version_command[1:],
version_substitutions),
candidate_version_regex)
if "urls" in deep_get(cni_data, DictPath(f"{cni}#{upgradetype}"), {}):
# We should probably use semver here instead
if version is not None and candidate_version is not None:
is_new_version = None
for v1, v2 in zip(version, candidate_version):
if v1 != v2:
if v1.isnumeric() and v2.isnumeric():
is_new_version = int(v1) < int(v2)
else:
is_new_version = v1 < v2
break
if is_new_version is None:
is_new_version = len(candidate_version) > len(version)
# pylint: disable-next=too-many-boolean-expressions
if (version is None or not version) \
or version is not None and (candidate_version is None or not candidate_version) \
or is_new_version:
new_version = "".join(candidate_version)
ansithemeprint([ANSIThemeStr("\n• ", "separator"),
ANSIThemeStr(f"Downloading {upgradetype} ", "action"),
ANSIThemeStr(f"{new_version}", "version")])
substitutions = {
"<<<version>>>": new_version,
"<<<arch>>>": arch,
"<<<context>>>": context,
}
kubectl_path = secure_which(FilePath("/usr/bin/kubectl"),
fallback_allowlist=["/etc/alternatives"],
security_policy=SecurityPolicy.ALLOWLIST_RELAXED)
if upgradetype == "CNI":
secure_mkdir(DEPLOYMENT_DIR)
directory = DEPLOYMENT_DIR.joinpath("cni")
permissions = 0o644
elif upgradetype == "executable":
directory = BINDIR
permissions = 0o755
else:
raise ValueError(f"Unknown upgradetype {upgradetype}; this is a programming error.")
secure_mkdir(directory)
for url in deep_get(cni_data, DictPath(f"{cni}#{upgradetype}#urls"), []):
download_url = deep_get(url, DictPath("url"), "")
checksum_url = deep_get(url, DictPath("checksum_url"), None)
checksum_type = deep_get(url, DictPath("checksum_type"), None)
filename = deep_get(url, DictPath("filename"), "")
download_url = substitute_string(download_url, substitutions)
checksum_url = substitute_string(checksum_url, substitutions)
filename = substitute_string(filename, substitutions)
ansithemeprint([ANSIThemeStr("\n • ", "separator"),
ANSIThemeStr("Downloading ", "subaction"),
ANSIThemeStr(f"{filename}", "version")])
check_and_print_status(download_files(directory,
[(download_url, filename, checksum_url, checksum_type)],
permissions=permissions))
if upgradetype == "CNI":
new_path = FilePath(directory).joinpath(filename)
args = [str(kubectl_path)]
kubectl_major_version, kubectl_minor_version, _kubectl_git_version, \
_server_major_version, _server_minor_version, _server_git_version = \
kubernetes_helper.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)
if kubectl_major_version <= 1 and kubectl_minor_version < 22:
args += ["create"]
else:
args += ["apply", "--server-side"]
args += ["-f", new_path]
patch_cni_call = deep_get(url, DictPath("patch"))
if patch_cni_call is not None:
ansithemeprint([ANSIThemeStr("\n • ", "separator"),
ANSIThemeStr("Patching ", "subaction"),
ANSIThemeStr(f"{filename}", "version")])
check_and_print_status(patch_cni_call(new_path, pod_network_cidr))
ansithemeprint([ANSIThemeStr("\n • ", "separator"),
ANSIThemeStr("Applying ", "subaction"),
ANSIThemeStr(f"{filename}", "version")])
if verbose:
# This should check whether kubectl is >= 1.22;
# otherwise we need to use create
check_and_print_status(execute_command(args))
else:
# This should check whether kubectl is >= 1.22;
# otherwise we need to use create
execute_command_with_response(args)
else:
ansithemeprint([ANSIThemeStr("No newer version available.", "default")])
elif install_command is not None and (version is None or len(version) == 0):
new_version = "".join(candidate_version)
ansithemeprint([ANSIThemeStr("\n• ", "separator"),
ANSIThemeStr(f"Installing {upgradetype} ", "action"),
ANSIThemeStr(f"{new_version}", "version")])
substitutions = {
"<<<version>>>": new_version,
"<<<arch>>>": arch,
"<<<context>>>": context,
}
check_and_print_status(execute_command(substitute_list(install_command, substitutions)))
elif upgrade_command is not None:
if version is None or version < candidate_version:
new_version = "".join(candidate_version)
ansithemeprint([ANSIThemeStr("\n• ", "separator"),
ANSIThemeStr(f"Upgrading {upgradetype} to ", "action"),
ANSIThemeStr(f"{new_version}", "version")])
substitutions = {
"<<<version>>>": new_version,
"<<<arch>>>": arch,
"<<<context>>>": context,
}
check_and_print_status(execute_command(substitute_list(upgrade_command, substitutions)))
else:
ansithemeprint([ANSIThemeStr("No newer version available.", "default")])
# pylint: disable-next=too-many-branches
def setup_cni(options: list[tuple[str, str]], args: list[str]) -> None:
"""
Install and configure the specified CNI.
Parameters:
options ([(opt, optarg)]): Options to use when executing this action
args ([str]): The CNI to install and configure
(optional; if not specified the default CNI will be used)
"""
# default options
confirm = True
reinstall = False
verbose = False
for opt, _optarg in options:
if opt == "--reinstall":
reinstall = True
elif opt == "-Y":