/
__init__.py
3194 lines (2784 loc) · 145 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright (c) 2020 ScyllaDB
# pylint: disable=too-many-arguments
# pylint: disable=too-many-lines
from __future__ import annotations
import os
import re
import abc
import json
import math
import shutil
import tempfile
import time
import base64
import random
import socket
import logging
import traceback
import contextlib
from pathlib import Path
from copy import deepcopy
from datetime import datetime
from difflib import unified_diff
from functools import cached_property, partialmethod, partial
from tempfile import NamedTemporaryFile, TemporaryDirectory
from textwrap import dedent
from threading import Lock, RLock
from typing import Optional, Union, List, Dict, Any, ContextManager, Type, Tuple, Callable
import yaml
import kubernetes as k8s
from kubernetes.client import exceptions as k8s_exceptions
from kubernetes.client import V1ConfigMap
from kubernetes.dynamic.resource import Resource, ResourceField, ResourceInstance, ResourceList, Subresource
import invoke
from invoke.exceptions import CommandTimedOut
from sdcm import sct_abs_path, cluster
from sdcm.cluster import DeadNode, ClusterNodesNotReady
from sdcm.provision.scylla_yaml.scylla_yaml import ScyllaYaml
from sdcm.sct_config import SCTConfiguration, init_and_verify_sct_config
from sdcm.test_config import TestConfig
from sdcm.db_stats import PrometheusDBStats
from sdcm.remote import LOCALRUNNER, NETWORK_EXCEPTIONS
from sdcm.remote.kubernetes_cmd_runner import (
KubernetesCmdRunner,
KubernetesPodRunner,
)
from sdcm.coredump import CoredumpExportFileThread
from sdcm.log import SDCMAdapter
from sdcm.mgmt import AnyManagerCluster
from sdcm.sct_events.database import DatabaseLogEvent
from sdcm.sct_events.filters import DbEventsFilter
from sdcm.sct_events.health import ClusterHealthValidatorEvent
from sdcm.sct_events.system import TestFrameworkEvent
from sdcm.utils import properties
import sdcm.utils.sstable.load_inventory as datasets
from sdcm.utils.adaptive_timeouts import adaptive_timeout, Operations
from sdcm.utils.ci_tools import get_test_name
from sdcm.utils.common import download_from_github, shorten_cluster_name, walk_thru_data
from sdcm.utils.k8s import (
add_pool_node_affinity,
convert_cpu_units_to_k8s_value,
convert_cpu_value_from_k8s_to_units,
convert_memory_units_to_k8s_value,
convert_memory_value_from_k8s_to_units,
get_helm_pool_affinity_values,
get_pool_affinity_modifiers,
get_preferred_pod_anti_affinity_values,
ApiCallRateLimiter,
JSON_PATCH_TYPE,
KubernetesOps,
KUBECTL_TIMEOUT,
HelmValues,
ScyllaPodsIPChangeTrackerThread,
TokenUpdateThread,
)
from sdcm.utils.decorators import log_run_info, retrying
from sdcm.utils.decorators import timeout as timeout_wrapper
from sdcm.utils.k8s.chaos_mesh import ChaosMesh
from sdcm.utils.remote_logger import get_system_logging_thread, CertManagerLogger, ScyllaOperatorLogger, \
KubectlClusterEventsLogger, ScyllaManagerLogger, KubernetesWrongSchedulingLogger, HaproxyIngressLogger
from sdcm.utils.sstable.load_utils import SstableLoadUtils
from sdcm.utils.version_utils import ComparableScyllaOperatorVersion
from sdcm.wait import wait_for
from sdcm.cluster_k8s.operator_monitoring import ScyllaOperatorLogMonitoring
ANY_KUBERNETES_RESOURCE = Union[ # pylint: disable=invalid-name
Resource, ResourceField, ResourceInstance, ResourceList, Subresource,
]
NAMESPACE_CREATION_LOCK = Lock()
NODE_INIT_LOCK = Lock()
CERT_MANAGER_TEST_CONFIG = sct_abs_path("sdcm/k8s_configs/cert-manager-test.yaml")
LOADER_POD_CONFIG_PATH = sct_abs_path("sdcm/k8s_configs/loaders/pod.yaml")
LOADER_STS_CONFIG_PATH = sct_abs_path("sdcm/k8s_configs/loaders/sts.yaml")
LOCAL_PROVISIONER_FILE = sct_abs_path("sdcm/k8s_configs/static-local-volume-provisioner.yaml")
LOCAL_MINIO_DIR = sct_abs_path("sdcm/k8s_configs/minio")
INGRESS_CONTROLLER_CONFIG_PATH = sct_abs_path("sdcm/k8s_configs/ingress-controller")
PROMETHEUS_OPERATOR_CONFIG_PATH = sct_abs_path("sdcm/k8s_configs/monitoring/prometheus-operator")
SCYLLA_MONITORING_CONFIG_PATH = sct_abs_path("sdcm/k8s_configs/monitoring/scylladbmonitoring-template.yaml")
SCYLLA_API_VERSION = "scylla.scylladb.com/v1"
SCYLLA_CLUSTER_RESOURCE_KIND = "ScyllaCluster"
DEPLOY_SCYLLA_CLUSTER_DELAY = 15 # seconds
SCYLLA_OPERATOR_NAMESPACE = "scylla-operator"
SCYLLA_MANAGER_NAMESPACE = "scylla-manager"
SCYLLA_NAMESPACE = "scylla"
INGRESS_CONTROLLER_NAMESPACE = "haproxy-controller"
PROMETHEUS_OPERATOR_NAMESPACE = "prometheus-operator"
LOADER_NAMESPACE = "sct-loaders"
MINIO_NAMESPACE = "minio"
SCYLLA_CONFIG_NAME = "scylla-config"
SCYLLA_AGENT_CONFIG_NAME = "scylla-agent-config"
K8S_LOCAL_VOLUME_PROVISIONER_VERSION = "0.3.0" # without 'v' prefix
SCYLLA_MANAGER_AGENT_VERSION_IN_SCYLLA_MANAGER = "3.2.6"
# NOTE: add custom annotations to a ServiceAccount used by a ScyllaCluster
# It is needed to make sure that annotations survive operator upgrades
SCYLLA_CLUSTER_SA_ANNOTATION_KEY_PREFIX = "sct-custom-annotation-key-"
SCYLLA_CLUSTER_SA_ANNOTATION_VALUE_PREFIX = "sct-custom-annotation-value-"
SCYLLA_CLUSTER_SA_ANNOTATIONS = {
f'{SCYLLA_CLUSTER_SA_ANNOTATION_KEY_PREFIX}1': f'{SCYLLA_CLUSTER_SA_ANNOTATION_VALUE_PREFIX}1',
f'{SCYLLA_CLUSTER_SA_ANNOTATION_KEY_PREFIX}2': f'{SCYLLA_CLUSTER_SA_ANNOTATION_VALUE_PREFIX}2',
}
# Resources that are used by container deployed by scylla-operator on scylla nodes
OPERATOR_CONTAINERS_RESOURCES = {
'cpu': 0.05,
'memory': 0.01,
}
# Other common resources which get deployed on each scylla node such as 'kube-proxy'
# EKS: between 130m-260m CPU
# GKE: between 200m-300m CPU and 250Mi RAM
# Above numbers are "explicit" reservations. So, reserve a bit more for other common pods.
COMMON_CONTAINERS_RESOURCES = {
'cpu': 0.5131,
'memory': 0.81,
}
SCYLLA_MANAGER_AGENT_RESOURCES = {
'cpu': 0.04,
'memory': 0.489, # 0.489 will give 500Mb as a result
}
LOGGER = logging.getLogger(__name__)
class CloudK8sNodePool(metaclass=abc.ABCMeta): # pylint: disable=too-many-instance-attributes
def __init__(
self,
k8s_cluster: 'KubernetesCluster',
name: str,
num_nodes: int,
instance_type: str,
image_type: str,
disk_size: int = None,
disk_type: str = None,
labels: dict = None,
taints: list = None,
is_deployed: bool = False):
self.k8s_cluster = k8s_cluster
self.name = name
self.num_nodes = int(num_nodes)
self.instance_type = instance_type
self.disk_size = disk_size
self.disk_type = disk_type
self.image_type = image_type
self.labels = labels
self.taints = taints
self.is_deployed = is_deployed
@property
def tags(self):
return self.k8s_cluster.tags
@abc.abstractmethod
def deploy(self):
pass
def deploy_and_wait_till_ready(self):
if not self.is_deployed:
self.deploy()
self.wait_for_nodes_readiness()
@abc.abstractmethod
def undeploy(self):
pass
@abc.abstractmethod
def resize(self, num_nodes: int):
pass
def __str__(self):
data = [f'name="{self.name}"', *[f'{param}="{value}"' for param, value in self.__dict__.items() if
param not in ['name', 'k8s_cluster']]]
return f"<{self.__class__.__name__}:{', '.join(data)}>"
@cached_property
def affinity_modifiers(self) -> List[Callable]:
return get_pool_affinity_modifiers(self.pool_label_name, self.name)
@cached_property
def helm_affinity_values(self) -> HelmValues:
return HelmValues(get_helm_pool_affinity_values(self.pool_label_name, self.name))
@cached_property
def pool_label_name(self) -> str:
return self.k8s_cluster.POOL_LABEL_NAME
@cached_property
def cpu_and_memory_capacity(self) -> Tuple[float, float]:
for item in self.k8s_cluster.k8s_core_v1_api.list_node().items:
if item.metadata.labels.get(self.pool_label_name, '') == self.name:
capacity = item.status.allocatable
return convert_cpu_value_from_k8s_to_units(capacity['cpu']), convert_memory_value_from_k8s_to_units(
capacity['memory'])
raise RuntimeError(f"{self.k8s_cluster.region_name}: Can't find any node for pool '{self.name}'")
@property
def cpu_capacity(self) -> float:
return self.cpu_and_memory_capacity[0]
@property
def memory_capacity(self) -> float:
return self.cpu_and_memory_capacity[1]
@property
def readiness_timeout(self) -> int:
return 10 + (10 * self.num_nodes)
@property
def nodes(self):
try:
return self.k8s_cluster.k8s_core_v1_api.list_node(label_selector=f'{self.pool_label_name}={self.name}')
except Exception as details: # pylint: disable=broad-except
self.k8s_cluster.log.debug("Failed to get nodes list: %s", str(details))
return {}
def wait_for_nodes_readiness(self):
readiness_timeout = self.readiness_timeout
@timeout_wrapper(
message=(
f"{self.k8s_cluster.region_name}: Wait for {self.num_nodes} node(s)"
f" in the '{self.name}' pool to be ready..."),
sleep_time=30,
timeout=readiness_timeout * 60)
def wait_nodes_are_ready():
# To make it more informative in worst case scenario made it repeat 5 times, by readiness_timeout // 5
result = self.k8s_cluster.kubectl_no_wait(
f"wait --timeout={self.readiness_timeout // 5}m -l {self.pool_label_name}={self.name} "
f"--for=condition=Ready node",
timeout=readiness_timeout // 5 * 60 + 10, verbose=False)
if result.stdout.count('condition met') != self.num_nodes:
raise RuntimeError('Not all nodes reported')
wait_nodes_are_ready()
class KubernetesCluster(metaclass=abc.ABCMeta): # pylint: disable=too-many-public-methods,too-many-instance-attributes
AUXILIARY_POOL_NAME = 'auxiliary-pool'
SCYLLA_POOL_NAME = 'scylla-pool'
MONITORING_POOL_NAME = 'monitoring-pool'
LOADER_POOL_NAME = 'loader-pool'
POOL_LABEL_NAME: str = None
IS_NODE_TUNING_SUPPORTED: bool = False
NODE_PREPARE_FILE = None
NODE_CONFIG_CRD_FILE = None
TOKEN_UPDATE_NEEDED = True
api_call_rate_limiter: Optional[ApiCallRateLimiter] = None
_cert_manager_journal_thread: Optional[CertManagerLogger] = None
_scylla_manager_journal_thread: Optional[ScyllaManagerLogger] = None
_scylla_operator_journal_thread: Optional[ScyllaOperatorLogger] = None
_scylla_operator_scheduling_thread: Optional[KubernetesWrongSchedulingLogger] = None
_haproxy_ingress_log_thread: Optional[HaproxyIngressLogger] = None
_scylla_cluster_events_threads: Dict[str, KubectlClusterEventsLogger] = {}
_scylla_operator_log_monitor_thread: Optional[ScyllaOperatorLogMonitoring] = None
_token_update_thread: Optional[TokenUpdateThread] = None
scylla_pods_ip_change_tracker_thread: Optional[ScyllaPodsIPChangeTrackerThread] = None
pools: Dict[str, CloudK8sNodePool]
scylla_pods_ip_mapping = {}
def __init__(self, params: dict, user_prefix: str = '', region_name: str = None, cluster_uuid: str = None):
self.test_config = TestConfig()
self.pools = {}
if cluster_uuid is None:
self.uuid = self.test_config.test_id()
else:
self.uuid = cluster_uuid
self.region_name = region_name
self.rack_name = "rack-1"
self.shortid = str(self.uuid)[:8]
self.name = f"{user_prefix}-{self.shortid}"
self.params = params
self.api_call_rate_limiter = None
self.k8s_scylla_cluster_name = self.params.get('k8s_scylla_cluster_name')
self.scylla_config_lock = RLock()
self.scylla_restart_required = False
self.scylla_cpu_limit = None
self.scylla_memory_limit = None
self.calculated_loader_cpu_limit = None
self.calculated_loader_memory_limit = None
self.calculated_loader_affinity_modifiers = []
self.perf_pods_labels = [
('app.kubernetes.io/name', 'scylla-node-config'),
('app.kubernetes.io/name', 'node-config'),
('scylla-operator.scylladb.com/node-config-job-type', 'Node'),
('scylla-operator.scylladb.com/node-config-job-type', 'Containers'),
]
self._scylla_cluster_events_threads = {}
self.chaos_mesh = ChaosMesh(self)
# NOTE: Following class attr(s) are defined for consumers of this class
# such as 'sdcm.utils.remote_logger.ScyllaOperatorLogger'.
_scylla_operator_namespace = SCYLLA_OPERATOR_NAMESPACE
_scylla_manager_namespace = SCYLLA_MANAGER_NAMESPACE
@cached_property
def log(self):
# return logging.getLogger(f"{__name__} | {self.region_name}")
return SDCMAdapter(LOGGER, extra={'prefix': self.region_name})
@cached_property
def tenants_number(self) -> int:
return self.params.get("k8s_tenants_num") or 1
@property
def allowed_labels_on_scylla_node(self):
# keep pods labels that are allowed to be scheduled on the Scylla node
return []
@cached_property
def cluster_backend(self):
return self.params.get("cluster_backend")
@property
def k8s_server_url(self) -> Optional[str]:
return None
@cached_property
def short_cluster_name(self):
return shorten_cluster_name(self.name, 40).replace('_', '-')
kubectl_cmd = partialmethod(KubernetesOps.kubectl_cmd)
apply_file = partialmethod(KubernetesOps.apply_file)
def kubectl_no_wait(self, *command, namespace=None, timeout=KUBECTL_TIMEOUT, remoter=None, ignore_status=False,
verbose=True):
return KubernetesOps.kubectl(self, *command, namespace=namespace, timeout=timeout, remoter=remoter,
ignore_status=ignore_status, verbose=verbose)
def kubectl(self, *command, namespace=None, timeout=KUBECTL_TIMEOUT, remoter=None, ignore_status=False,
verbose=True):
if self.api_call_rate_limiter:
self.api_call_rate_limiter.wait()
return KubernetesOps.kubectl(self, *command, namespace=namespace, timeout=timeout, remoter=remoter,
ignore_status=ignore_status, verbose=verbose)
def kubectl_wait(self, *command, namespace=None, timeout=KUBECTL_TIMEOUT, remoter=None, verbose=True):
"""
We use kubectl wait to wait till all resources get into proper state
there are two problems with this:
1. kubectl wait fails when no resource matched criteria
2. if resources are provisioned gradually, kubectl wait can slip thrue crack when half of the resource
provisioned and the rest is not even deployed
This function is to address these problem by wrapping 'kubectl wait' and make it restarted when no resource
are there to tackle problem #1 and track number of resources it reported and wait+rerun if resource number
had changed to tackle problem #2
"""
last_resource_count = -1
@timeout_wrapper(timeout=timeout, sleep_time=5)
def wait_body():
nonlocal last_resource_count
result = self.kubectl('wait --timeout=1m', *command, namespace=namespace, timeout=timeout, remoter=remoter,
verbose=verbose)
current_resource_count = result.stdout.count('condition met')
if current_resource_count != last_resource_count:
last_resource_count = current_resource_count
time.sleep(10)
raise RuntimeError("Retry since matched resource count has changed")
return result
return wait_body()
def kubectl_multi_cmd(self, *command, namespace=None, timeout=KUBECTL_TIMEOUT, remoter=None, ignore_status=False,
verbose=True):
if self.api_call_rate_limiter:
self.api_call_rate_limiter.wait()
return KubernetesOps.kubectl_multi_cmd(self, *command, namespace=namespace, timeout=timeout, remoter=remoter,
ignore_status=ignore_status, verbose=verbose)
@property
def helm(self):
if self.api_call_rate_limiter:
self.api_call_rate_limiter.wait()
return partial(self.test_config.tester_obj().localhost.helm, self)
@property
def helm_install(self):
if self.api_call_rate_limiter:
self.api_call_rate_limiter.wait()
return partial(self.test_config.tester_obj().localhost.helm_install, self)
@property
def helm_upgrade(self):
if self.api_call_rate_limiter:
self.api_call_rate_limiter.wait()
return partial(self.test_config.tester_obj().localhost.helm_upgrade, self)
@cached_property
def kube_config_dir_path(self):
_kube_config_dir_path = os.path.join(os.path.expanduser(self.logdir), ".kube")
os.makedirs(_kube_config_dir_path, exist_ok=True)
return _kube_config_dir_path
@cached_property
def kube_config_path(self):
return os.path.join(self.kube_config_dir_path, "config")
@cached_property
def kubectl_token_path(self):
return os.path.join(self.kube_config_dir_path, "token")
@cached_property
def helm_dir_path(self):
_helm_dir_path = os.path.join(os.path.dirname(self.kube_config_dir_path), ".helm")
os.makedirs(_helm_dir_path, exist_ok=True)
return _helm_dir_path
def create_namespace(self, namespace: str) -> None:
self.log.info("Create '%s' namespace", namespace)
namespaces = yaml.safe_load(self.kubectl("get namespaces -o yaml").stdout)
if not [ns["metadata"]["name"] for ns in namespaces["items"] if ns["metadata"]["name"] == namespace]:
self.kubectl(f"create namespace {namespace}")
else:
self.log.warning("The '%s' namespace already exists.")
@cached_property
def cert_manager_log(self) -> str:
return os.path.join(self.logdir, "cert_manager.log")
@cached_property
def scylla_manager_log(self) -> str:
return os.path.join(self.logdir, "scylla_manager.log")
@cached_property
def haproxy_ingress_log(self) -> str:
return os.path.join(self.logdir, "haproxy_ingress.log")
def start_cert_manager_journal_thread(self) -> None:
self._cert_manager_journal_thread = CertManagerLogger(self, self.cert_manager_log)
self._cert_manager_journal_thread.start()
def start_scylla_manager_journal_thread(self):
self._scylla_manager_journal_thread = ScyllaManagerLogger(self, self.scylla_manager_log)
self._scylla_manager_journal_thread.start()
def start_haproxy_ingress_log_thread(self) -> None:
self._haproxy_ingress_log_thread = HaproxyIngressLogger(self, self.haproxy_ingress_log)
self._haproxy_ingress_log_thread.start()
def set_nodeselector_for_deployments(self, pool_name: str,
namespace: str = "kube-system",
selector: str = "") -> None:
"""Sets node selector for deployment objects in a namespace.
pool_name: any pool name. For example 'auxiliary-pool' in EKS or 'default-pool' in GKE.
namespace: any namespace to look for deployments.
selector: any selector to use for filtering deployments in a namespace.
Example: 'foo=bar' or '' (empty string means 'all').
Use case: deploying Scylla cluster on EKS or GKE backends we don't want to have
unexpected pods be placed onto Scylla K8S nodes. Also, we don't want to stick
to any of deployment names in case it's name or number changes.
"""
data = {"spec": {"template": {"spec": {"nodeSelector": {
self.POOL_LABEL_NAME: pool_name,
}}}}}
deployment_names = self.kubectl(
f"get deployments -l '{selector}' --no-headers -o custom-columns=:.metadata.name",
namespace=namespace).stdout.split()
for deployment_name in deployment_names:
self.kubectl(
f"patch deployments {deployment_name} -p '{json.dumps(data)}'",
namespace=namespace)
@log_run_info
def deploy_cert_manager(self, pool_name: str = None) -> None:
cert_manager_namespace = "cert-manager"
if not self.params.get('reuse_cluster'):
if pool_name is None:
pool_name = self.AUXILIARY_POOL_NAME
self.log.info("Deploy cert-manager")
self.create_namespace(cert_manager_namespace)
self.log.debug(self.helm("repo add jetstack https://charts.jetstack.io"))
if pool_name:
values_dict = get_helm_pool_affinity_values(self.POOL_LABEL_NAME, pool_name)
values_dict["cainjector"] = {"affinity": values_dict["affinity"]}
values_dict["webhook"] = {"affinity": values_dict["affinity"]}
helm_values = HelmValues(values_dict)
else:
helm_values = HelmValues()
helm_values.set('installCRDs', True)
self.log.debug(self.helm(
"install cert-manager jetstack/cert-manager"
f" --version v{self.params.get('k8s_cert_manager_version')}",
namespace=cert_manager_namespace, values=helm_values))
self.kubectl_wait("--all --for=condition=Ready pod", namespace="cert-manager",
timeout=600)
wait_for(
self.check_if_cert_manager_fully_functional,
text='Waiting for cert-manager to become fully operational',
timeout=10 * 60,
step=10,
throw_exc=True)
self.start_cert_manager_journal_thread()
def get_latest_chart_version(self, local_chart_path: str) -> str:
all_versions = yaml.safe_load(self.helm(
f"search repo {local_chart_path} --devel --versions -o yaml"))
assert isinstance(all_versions, list), f"Expected list of data, got: {type(all_versions)}"
# NOTE: ignore versions like 'v1.8.0-alpha.0' because they refer to the oldest full version
# in each 'minor' family.
current_newest_version, current_newest_version_str = None, ''
for version_object in all_versions:
if version_object["version"].count('-') == 1:
continue
if ComparableScyllaOperatorVersion(version_object["version"]) > (
current_newest_version or '0.0.0'):
current_newest_version = ComparableScyllaOperatorVersion(version_object["version"])
current_newest_version_str = version_object["version"]
continue
return current_newest_version_str
@cached_property
def scylla_operator_chart_version(self):
self.log.debug(self.helm(
f"repo add scylla-operator {self.params.get('k8s_scylla_operator_helm_repo')}"))
# NOTE: 'scylla-operator' and 'scylla-manager' chart versions are always the same.
# So, we can reuse one for another.
chart_version = self.params.get("k8s_scylla_operator_chart_version").strip().lower()
if chart_version in ("", "latest"):
chart_version = self.get_latest_chart_version("scylla-operator/scylla-operator")
self.log.info(
"Using automatically found following latest scylla-operator chart version: %s",
chart_version)
else:
self.log.info(
"Using following predefined scylla-operator chart version: %s", chart_version)
return chart_version
def get_operator_image(self, repo: str = '', chart_version: str = '') -> str:
if image := self.params.get("k8s_scylla_operator_docker_image"):
return image
# Get 'appVersion' field from the Helm chart which stores image's tag
repo = repo or self.params.get('k8s_scylla_operator_helm_repo')
chart_name = "scylla-operator"
chart_version = chart_version or self.scylla_operator_chart_version
chart_info = self.helm(
f"show chart {chart_name} --devel --repo {repo} --version {chart_version}")
for line in chart_info.split("\n"):
if line.startswith("appVersion:"):
# NOTE: 'appVersion' key may have different formats for it's value.
# Value may or may not be wrapped in quotes.
# $ helm show chart scylla-operator --devel --repo %repo% --version v1.6.0-rc.0
# apiVersion: v2
# appVersion: "1.6"
# ...
#
# $ helm show chart scylla-operator --devel --repo %repo% --version v1.5.0-rc.0
# apiVersion: v2
# appVersion: 1.5.0-rc.0
# ...
#
# Details: https://helm.sh/docs/topics/charts/#the-appversion-field
found_app_version = line.split(':')[-1].strip().replace('"', '').replace("'", "")
return f"scylladb/scylla-operator:{found_app_version}"
raise ValueError(
f"Cannot get operator image version from the '{chart_name}' chart located at "
f"'{repo}' having '{chart_version}' version")
@log_run_info
def deploy_scylla_manager(self, pool_name: str = None) -> None:
# Calculate options values which must be set
#
# image.tag -> self.params.get('mgmt_docker_image').split(':')[-1]
# controllerImage.repository -> self.params.get(
# 'k8s_scylla_operator_docker_image').split('/')[0]
# controllerImage.tag -> self.params.get(
# 'k8s_scylla_operator_docker_image').split(':')[-1]
if not self.params.get('reuse_cluster'):
self.log.info("Deploy scylla-manager")
helm_affinity = get_helm_pool_affinity_values(
self.POOL_LABEL_NAME, pool_name) if pool_name else {}
values = HelmValues(**helm_affinity)
values.set("controllerAffinity", helm_affinity.get("affinity", {}))
storage_config = {"capacity": "10Gi"}
if self.cluster_backend == "k8s-eks":
storage_config["storageClassName"] = "gp3-3k-iops"
values.set("scylla", {
"developerMode": True,
"datacenter": "manager-dc",
"agentImage": {"tag": SCYLLA_MANAGER_AGENT_VERSION_IN_SCYLLA_MANAGER},
"racks": [{
"name": "manager-rack",
"members": 1,
"placement": helm_affinity["affinity"],
"storage": storage_config,
"resources": {
"limits": {"cpu": 1, "memory": "200Mi"},
"requests": {"cpu": 1, "memory": "200Mi"},
},
}],
})
mgmt_docker_image_tag = self.params.get('mgmt_docker_image').split(':')[-1]
if mgmt_docker_image_tag:
values.set('image.tag', mgmt_docker_image_tag)
scylla_operator_repo_base = self.params.get(
'k8s_scylla_operator_docker_image').rsplit('/', 1)[0]
if scylla_operator_repo_base:
values.set('controllerImage.repository', scylla_operator_repo_base)
scylla_operator_image_tag = self.params.get(
'k8s_scylla_operator_docker_image').split(':', 1)[-1]
if scylla_operator_image_tag:
values.set('controllerImage.tag', scylla_operator_image_tag)
self.create_namespace(SCYLLA_MANAGER_NAMESPACE)
# Install and wait for initialization of the Scylla Manager chart
self.log.debug(self.helm_install(
target_chart_name="scylla-manager",
source_chart_name="scylla-operator/scylla-manager",
version=self.scylla_operator_chart_version,
use_devel=True,
values=values,
namespace=SCYLLA_MANAGER_NAMESPACE,
))
self.kubectl_wait(
"--all --for=condition=Ready pod",
namespace=SCYLLA_MANAGER_NAMESPACE,
timeout=600,
)
self.start_scylla_manager_journal_thread()
def check_if_cert_manager_fully_functional(self) -> bool:
# Cert-manager readiness status does not guarantee that it is fully operational
# This function checks it if is operational via deploying ca and issuing certificate
try:
self.apply_file(CERT_MANAGER_TEST_CONFIG)
return True
finally:
self.kubectl(f'delete -f {CERT_MANAGER_TEST_CONFIG}', ignore_status=True)
@property
def scylla_operator_log(self) -> str:
return os.path.join(self.logdir, "scylla_operator.log")
def scylla_cluster_event_log(self, namespace: str = SCYLLA_NAMESPACE) -> str:
return os.path.join(self.logdir, f"{namespace}_cluster_events.log")
def start_scylla_operator_journal_thread(self) -> None:
self._scylla_operator_journal_thread = ScyllaOperatorLogger(self, self.scylla_operator_log)
self._scylla_operator_journal_thread.start()
self._scylla_operator_scheduling_thread = KubernetesWrongSchedulingLogger(self, self.scylla_operator_log)
self._scylla_operator_scheduling_thread.start()
self._scylla_operator_log_monitor_thread = ScyllaOperatorLogMonitoring(self)
self._scylla_operator_log_monitor_thread.start()
def start_scylla_cluster_events_thread(self, namespace: str = SCYLLA_NAMESPACE) -> None:
self._scylla_cluster_events_threads[namespace] = KubectlClusterEventsLogger(
self, self.scylla_cluster_event_log(namespace=namespace), namespace=namespace)
self._scylla_cluster_events_threads[namespace].start()
@log_run_info
def deploy_scylla_operator(self, pool_name: str = None) -> None:
if not self.params.get('reuse_cluster'):
if pool_name is None:
pool_name = self.AUXILIARY_POOL_NAME
affinity_rules = {
"affinity": get_preferred_pod_anti_affinity_values("scylla-operator"),
"webhookServerAffinity": get_preferred_pod_anti_affinity_values("webhook-server"),
}
if pool_name:
add_pool_node_affinity(affinity_rules["affinity"], self.POOL_LABEL_NAME, pool_name)
affinity_rules["webhookServerAffinity"]["nodeAffinity"] = (
affinity_rules["affinity"]["nodeAffinity"])
values = HelmValues(**affinity_rules)
if ComparableScyllaOperatorVersion(
self.scylla_operator_chart_version.split("-")[0]) > "1.3.0":
# NOTE: following is supported starting with operator-1.4
values.set("logLevel", 4)
# Calculate options values which must be set
#
# image.repository -> self.params.get('k8s_scylla_operator_docker_image').split('/')[0]
# image.tag -> self.params.get('k8s_scylla_operator_docker_image').split(':')[-1]
scylla_operator_repo_base = self.params.get(
'k8s_scylla_operator_docker_image').rsplit('/', 1)[0]
if scylla_operator_repo_base:
values.set('image.repository', scylla_operator_repo_base)
scylla_operator_image_tag = self.params.get(
'k8s_scylla_operator_docker_image').split(':', 1)[-1]
if scylla_operator_image_tag:
values.set('image.tag', scylla_operator_image_tag)
# Install and wait for initialization of the Scylla Operator chart
self.log.info("Deploy Scylla Operator")
self.create_namespace(SCYLLA_OPERATOR_NAMESPACE)
self.log.debug(self.helm_install(
target_chart_name="scylla-operator",
source_chart_name="scylla-operator/scylla-operator",
version=self.scylla_operator_chart_version,
use_devel=True,
namespace=SCYLLA_OPERATOR_NAMESPACE,
values=values
))
scylla_operator_version = self.scylla_operator_chart_version.split("-")[0]
enable_tls = 'true' if self.params.get('k8s_enable_tls') else 'false'
if ComparableScyllaOperatorVersion(scylla_operator_version) >= "1.8.0":
patch_cmd = (
'patch deployment scylla-operator --type=json -p=\'[{"op": "add",'
' "path": "/spec/template/spec/containers/0/args/-", '
f'"value": "--feature-gates=AutomaticTLSCertificates={enable_tls}" }}]\' ')
self.kubectl(patch_cmd, namespace=SCYLLA_OPERATOR_NAMESPACE)
if enable_tls == 'true' and ComparableScyllaOperatorVersion(scylla_operator_version) >= "1.9.0":
# around 10 keys that need to be cached per cluster
crypto_key_buffer_size = self.params.get('k8s_tenants_num') * 10
for flag in (f"--crypto-key-buffer-size-min={crypto_key_buffer_size}",
f"--crypto-key-buffer-size-max={crypto_key_buffer_size}"):
patch_obj = [{
"op": "add",
"path": "/spec/template/spec/containers/0/args/-",
"value": flag
}]
patch_cmd = f"patch deployment scylla-operator --type=json -p='{json.dumps(patch_obj)}'"
self.kubectl(patch_cmd, namespace=SCYLLA_OPERATOR_NAMESPACE)
KubernetesOps.wait_for_pods_readiness(
kluster=self,
total_pods=lambda pods: pods > 0,
readiness_timeout=5,
namespace=SCYLLA_OPERATOR_NAMESPACE
)
# Start the Scylla Operator logging thread
self.start_scylla_operator_journal_thread()
@log_run_info
def upgrade_scylla_operator(self, new_helm_repo: str,
new_chart_version: str,
new_docker_image: str = '') -> None:
self.log.info(
"Upgrade Scylla Operator using '%s' helm chart and '%s' docker image\n"
"Helm repo: %s", new_chart_version, new_docker_image, new_helm_repo)
local_repo_name = "scylla-operator-upgrade"
self.log.debug(self.helm(f"repo add {local_repo_name} {new_helm_repo}"))
self.helm('repo update')
# Calculate new chart name if it is not specific
if new_chart_version in ("", "latest"):
new_chart_version = self.get_latest_chart_version(f"{local_repo_name}/scylla-operator")
self.log.info(
"Using automatically found following latest scylla-operator "
"upgrade chart version: %s", new_chart_version)
else:
self.log.info(
"Using following predefined scylla-operator upgrade chart version: %s",
new_chart_version)
# Upgrade CRDs if new chart version is newer than v1.5.0
# Helm doesn't do CRD 'upgrades', only 'creations'.
# Details:
# https://helm.sh/docs/chart_best_practices/custom_resource_definitions/#some-caveats-and-explanations
if ComparableScyllaOperatorVersion(new_chart_version.split("-")[0]) > "1.5.0":
self.log.info("Upgrade Scylla Operator CRDs: START")
try:
with TemporaryDirectory() as tmpdir:
self.helm(
f"pull {local_repo_name}/scylla-operator --devel --untar "
f"--version {new_chart_version} --destination {tmpdir}")
crd_basedir = os.path.join(tmpdir, 'scylla-operator/crds')
for current_file in os.listdir(crd_basedir):
if not (current_file.endswith(".yaml") or current_file.endswith(".yml")):
continue
self.apply_file(
os.path.join(crd_basedir, current_file), modifiers=[], envsubst=False)
except Exception as exc: # pylint: disable=broad-except
self.log.debug("Upgrade Scylla Operator CRDs: Exception: %s", exc)
self.log.info("Upgrade Scylla Operator CRDs: END")
# Get existing scylla-operator helm chart values
values = HelmValues(json.loads(self.helm(
"get values scylla-operator -o json", namespace=SCYLLA_OPERATOR_NAMESPACE)))
if ComparableScyllaOperatorVersion(new_chart_version.split("-")[0]) > "1.3.0":
# NOTE: following is supported starting with operator-1.4
values.set("logLevel", 4)
# NOTE: Apply new image repo if provided or set default one redefining base value
# example structure: scylladb/scylla-operator:latest
values.set('image.repository', new_docker_image.split('/')[0].strip() or 'scylladb')
# NOTE: Set operator_image_tag even if it is empty, we need to redefine base operator image
values.set('image.tag', new_docker_image.split(':')[-1].strip())
# Upgrade Scylla Operator using Helm chart
self.log.debug(self.helm_upgrade(
target_chart_name="scylla-operator",
source_chart_name=f"{local_repo_name}/scylla-operator",
version=new_chart_version,
use_devel=True,
namespace=SCYLLA_OPERATOR_NAMESPACE,
values=values,
))
if self.params.get('k8s_enable_tls') and ComparableScyllaOperatorVersion(
self.scylla_operator_chart_version.split("-")[0]) >= "1.8.0":
patch_cmd = ('patch deployment scylla-operator --type=json -p=\'[{"op": "add",'
'"path": "/spec/template/spec/containers/0/args/-", '
'"value": "--feature-gates=AutomaticTLSCertificates=true" }]\' ')
self.kubectl(patch_cmd, namespace=SCYLLA_OPERATOR_NAMESPACE)
time.sleep(5)
self.kubectl("rollout status deployment scylla-operator",
namespace=SCYLLA_OPERATOR_NAMESPACE)
def check_scylla_cluster_sa_annotations(self, namespace: str = SCYLLA_NAMESPACE):
# Make sure that ScyllaCluster ServiceAccount annotations stay unchanged
raw_sa_data = self.kubectl(
f"get sa {self.params.get('k8s_scylla_cluster_name')}-member -o yaml",
namespace=namespace).stdout
sa_data = yaml.safe_load(raw_sa_data)
error_msg = (
"ServiceAccount annotations don't have expected values.\n"
f"Expected: {SCYLLA_CLUSTER_SA_ANNOTATIONS}\n"
f"Actual: {sa_data['metadata']['annotations']}"
)
for annotation_key, annotation_value in SCYLLA_CLUSTER_SA_ANNOTATIONS.items():
assert sa_data["metadata"]["annotations"].get(annotation_key) == annotation_value, error_msg
@log_run_info
def deploy_minio_s3_backend(self):
if not self.params.get('reuse_cluster'):
self.log.info('Deploy minio s3-like backend server')
self.create_namespace(MINIO_NAMESPACE)
values = HelmValues({})
values.set('persistence.size', self.params.get("k8s_minio_storage_size"))
self.log.debug(self.helm_install(
target_chart_name="minio",
source_chart_name=LOCAL_MINIO_DIR,
namespace=MINIO_NAMESPACE,
values=values,
))
wait_for(lambda: self.minio_ip_address, text='Waiting for minio pod to popup',
timeout=120, throw_exc=True)
self.kubectl_wait("-l app=minio --for=condition=Ready pod",
timeout=600, namespace=MINIO_NAMESPACE)
def get_scylla_cluster_helm_values(self, cpu_limit, memory_limit, pool_name: str = None,
cluster_name=None) -> HelmValues:
mgmt_agent_cpu_limit = convert_cpu_units_to_k8s_value(SCYLLA_MANAGER_AGENT_RESOURCES['cpu'])
mgmt_agent_memory_limit = convert_memory_units_to_k8s_value(
SCYLLA_MANAGER_AGENT_RESOURCES['memory'])
if not cluster_name:
cluster_name = self.params.get('k8s_scylla_cluster_name')
placement = add_pool_node_affinity({}, self.POOL_LABEL_NAME, pool_name) if pool_name else {}
pod_affinity_term = {
"topologyKey": "kubernetes.io/hostname",
"labelSelector": {"matchExpressions": [
{"key": "scylla/cluster", "operator": "In", "values": [cluster_name]},
{"key": "app.kubernetes.io/name", "operator": "In", "values": ["scylla"]},
]}
}
if self.tenants_number < 2:
placement["podAntiAffinity"] = {"preferredDuringSchedulingIgnoredDuringExecution": [{
"weight": 100,
"podAffinityTerm": pod_affinity_term,
}]}
else:
placement["podAntiAffinity"] = {"requiredDuringSchedulingIgnoredDuringExecution": [
pod_affinity_term,
]}
placement["tolerations"] = [{
"key": "role",
"value": "scylla-clusters",
"operator": "Equal",
"effect": "NoSchedule",
}]
dns_domains = []
expose_options = {}
if ComparableScyllaOperatorVersion(self.scylla_operator_chart_version.split("-")[0]) >= "1.11.0":
if k8s_db_node_service_type := self.params.get("k8s_db_node_service_type"):
expose_options["nodeService"] = {"type": k8s_db_node_service_type}
for broadcast_direction_type in ("node", "client"):
if ip_type := self.params.get(f"k8s_db_node_to_{broadcast_direction_type}_broadcast_ip_type"):
if "broadcastOptions" not in expose_options:
expose_options["broadcastOptions"] = {}
expose_options["broadcastOptions"][f"{broadcast_direction_type}s"] = {"type": ip_type}
if self.params.get('k8s_enable_sni') and ComparableScyllaOperatorVersion(
self.scylla_operator_chart_version.split("-")[0]) >= "1.8.0":
dns_domains = [f"{cluster_name}.sct.scylladb.com"]
expose_options = {"cql": {"ingress": {
"annotations": {
"haproxy.org/scale-server-slots": "1",
"haproxy.org/ssl-passthrough": "true",
},
"disabled": False,
"ingressClassName": "haproxy",
}}}
# NOTE: fs.aio-max-nr's value is defined in the scylla repo here:
# dist/common/sysctl.d/99-scylla-aio.conf
# Scylla 5.0+ has it as '30000000'
sysctls = ["fs.aio-max-nr=300000000", ]
if self.params.get('print_kernel_callstack'):
sysctls += ["kernel.perf_event_paranoid=0", ]
return HelmValues({
'nameOverride': '',
'fullnameOverride': cluster_name,
'scyllaImage': {
'repository': self.params.get('docker_image'),
'tag': self.params.get('scylla_version')
},
'agentImage': {
'repository': 'scylladb/scylla-manager-agent',
'tag': self.params.get('scylla_mgmt_agent_version')
},
'serviceAccount': {
'create': True,
'annotations': SCYLLA_CLUSTER_SA_ANNOTATIONS,
'name': f"{cluster_name}-member"
},
'alternator': {
'enabled': self.params.get("k8s_enable_alternator") or False,
'insecureEnableHTTP': True,
'insecureDisableAuthorization': not (
self.params.get("alternator_enforce_authorization") or False),
**({"writeIsolation": self.params.get("alternator_write_isolation")}
if self.params.get("alternator_write_isolation") else {}),
},
'developerMode': False,
'cpuset': True,
'hostNetworking': False,
'automaticOrphanedNodeCleanup': True,
'sysctls': sysctls,
'serviceMonitor': {
'create': False
},
'datacenter': self.region_name,
'dnsDomains': dns_domains,
'exposeOptions': expose_options,
'racks': [
{
'name': self.rack_name,
'scyllaConfig': SCYLLA_CONFIG_NAME,
'scyllaAgentConfig': SCYLLA_AGENT_CONFIG_NAME,
'members': 0,
'storage': {
'storageClassName': self.params.get('k8s_scylla_disk_class'),
'capacity': f"{self.params.get('k8s_scylla_disk_gi')}Gi"
},
'resources': {
'limits': {