/
kubernetes_tools.py
1945 lines (1731 loc) · 71.5 KB
/
kubernetes_tools.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
# Copyright 2015-2018 Yelp Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import copy
import hashlib
import itertools
import json
import logging
import math
import os
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List
from typing import Mapping
from typing import MutableMapping
from typing import NamedTuple
from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Union
import requests
import service_configuration_lib
from kubernetes import client as kube_client
from kubernetes import config as kube_config
from kubernetes.client import models
from kubernetes.client import V1AWSElasticBlockStoreVolumeSource
from kubernetes.client import V1beta1PodDisruptionBudget
from kubernetes.client import V1beta1PodDisruptionBudgetSpec
from kubernetes.client import V1Capabilities
from kubernetes.client import V1ConfigMap
from kubernetes.client import V1Container
from kubernetes.client import V1ContainerPort
from kubernetes.client import V1DeleteOptions
from kubernetes.client import V1Deployment
from kubernetes.client import V1DeploymentSpec
from kubernetes.client import V1DeploymentStrategy
from kubernetes.client import V1EnvVar
from kubernetes.client import V1EnvVarSource
from kubernetes.client import V1ExecAction
from kubernetes.client import V1Handler
from kubernetes.client import V1HostPathVolumeSource
from kubernetes.client import V1HTTPGetAction
from kubernetes.client import V1LabelSelector
from kubernetes.client import V1Lifecycle
from kubernetes.client import V1Namespace
from kubernetes.client import V1Node
from kubernetes.client import V1ObjectFieldSelector
from kubernetes.client import V1ObjectMeta
from kubernetes.client import V1PersistentVolumeClaim
from kubernetes.client import V1PersistentVolumeClaimSpec
from kubernetes.client import V1Pod
from kubernetes.client import V1PodSpec
from kubernetes.client import V1PodTemplateSpec
from kubernetes.client import V1Probe
from kubernetes.client import V1ReplicaSet
from kubernetes.client import V1ResourceRequirements
from kubernetes.client import V1RollingUpdateDeployment
from kubernetes.client import V1Secret
from kubernetes.client import V1SecretKeySelector
from kubernetes.client import V1SecurityContext
from kubernetes.client import V1StatefulSet
from kubernetes.client import V1StatefulSetSpec
from kubernetes.client import V1TCPSocketAction
from kubernetes.client import V1Volume
from kubernetes.client import V1VolumeMount
from kubernetes.client import V2beta1CrossVersionObjectReference
from kubernetes.client import V2beta1ExternalMetricSource
from kubernetes.client import V2beta1HorizontalPodAutoscaler
from kubernetes.client import V2beta1HorizontalPodAutoscalerCondition
from kubernetes.client import V2beta1HorizontalPodAutoscalerSpec
from kubernetes.client import V2beta1MetricSpec
from kubernetes.client import V2beta1PodsMetricSource
from kubernetes.client import V2beta1ResourceMetricSource
from kubernetes.client.models import V2beta1HorizontalPodAutoscalerStatus
from kubernetes.client.rest import ApiException
from paasta_tools.async_utils import async_timeout
from paasta_tools.long_running_service_tools import host_passes_blacklist
from paasta_tools.long_running_service_tools import host_passes_whitelist
from paasta_tools.long_running_service_tools import InvalidHealthcheckMode
from paasta_tools.long_running_service_tools import load_service_namespace_config
from paasta_tools.long_running_service_tools import LongRunningServiceConfig
from paasta_tools.long_running_service_tools import LongRunningServiceConfigDict
from paasta_tools.long_running_service_tools import ServiceNamespaceConfig
from paasta_tools.marathon_tools import AutoscalingParamsDict
from paasta_tools.secret_providers import BaseSecretProvider
from paasta_tools.secret_tools import get_secret_name_from_ref
from paasta_tools.secret_tools import is_secret_ref
from paasta_tools.secret_tools import is_shared_secret
from paasta_tools.secret_tools import SHARED_SECRET_SERVICE
from paasta_tools.utils import AwsEbsVolume
from paasta_tools.utils import BranchDictV2
from paasta_tools.utils import decompose_job_id
from paasta_tools.utils import deep_merge_dictionaries
from paasta_tools.utils import DEFAULT_SOA_DIR
from paasta_tools.utils import DeployBlacklist
from paasta_tools.utils import DeployWhitelist
from paasta_tools.utils import DockerVolume
from paasta_tools.utils import get_code_sha_from_dockerurl
from paasta_tools.utils import get_config_hash
from paasta_tools.utils import InvalidJobNameError
from paasta_tools.utils import load_system_paasta_config
from paasta_tools.utils import load_v2_deployments_json
from paasta_tools.utils import NoConfigurationForServiceError
from paasta_tools.utils import PaastaNotConfiguredError
from paasta_tools.utils import PersistentVolume
from paasta_tools.utils import SystemPaastaConfig
from paasta_tools.utils import time_cache
from paasta_tools.utils import VolumeWithMode
log = logging.getLogger(__name__)
KUBE_CONFIG_PATH = "/etc/kubernetes/admin.conf"
YELP_ATTRIBUTE_PREFIX = "yelp.com/"
PAASTA_ATTRIBUTE_PREFIX = "paasta.yelp.com/"
CONFIG_HASH_BLACKLIST = {"replicas"}
KUBE_DEPLOY_STATEGY_MAP = {
"crossover": "RollingUpdate",
"downthenup": "Recreate",
"brutal": "RollingUpdate",
}
HACHECK_POD_NAME = "hacheck"
KUBERNETES_NAMESPACE = "paasta"
DISCOVERY_ATTRIBUTES = {"region", "superregion", "ecosystem", "habitat"}
# For detail, https://github.com/kubernetes-client/python/issues/553
# This hack should be removed when the issue got fixed.
# This is no better way to work around rn.
class MonkeyPatchAutoScalingConditions(V2beta1HorizontalPodAutoscalerStatus):
@property
def conditions(self) -> Sequence[V2beta1HorizontalPodAutoscalerCondition]:
return super().conditions()
@conditions.setter
def conditions(
self, conditions: Optional[Sequence[V2beta1HorizontalPodAutoscalerCondition]]
) -> None:
self._conditions = list() if conditions is None else conditions
models.V2beta1HorizontalPodAutoscalerStatus = MonkeyPatchAutoScalingConditions
class KubeKind(NamedTuple):
singular: str
plural: str
class KubeDeployment(NamedTuple):
service: str
instance: str
git_sha: str
config_sha: str
replicas: int
class KubeCustomResource(NamedTuple):
service: str
instance: str
config_sha: str
kind: str
namespace: str
name: str
class KubeService(NamedTuple):
name: str
instance: str
port: int
pod_ip: str
registrations: Sequence[str]
class CustomResourceDefinition(NamedTuple):
file_prefix: str
version: str
kube_kind: KubeKind
group: str
def _set_disrupted_pods(self: Any, disrupted_pods: Mapping[str, datetime]) -> None:
"""Private function used to patch the setter for V1beta1PodDisruptionBudgetStatus.
Can be removed once https://github.com/kubernetes-client/python/issues/466 is resolved
"""
self._disrupted_pods = disrupted_pods
class KubernetesDeploymentConfigDict(LongRunningServiceConfigDict, total=False):
bounce_method: str
bounce_margin_factor: float
bounce_health_params: Dict[str, Any]
service_account_name: str
autoscaling: AutoscalingParamsDict
horizontal_autoscaling: Dict[str, Any]
def load_kubernetes_service_config_no_cache(
service: str,
instance: str,
cluster: str,
load_deployments: bool = True,
soa_dir: str = DEFAULT_SOA_DIR,
) -> "KubernetesDeploymentConfig":
"""Read a service instance's configuration for kubernetes.
If a branch isn't specified for a config, the 'branch' key defaults to
paasta-${cluster}.${instance}.
:param name: The service name
:param instance: The instance of the service to retrieve
:param cluster: The cluster to read the configuration for
:param load_deployments: A boolean indicating if the corresponding deployments.json for this service
should also be loaded
:param soa_dir: The SOA configuration directory to read from
:returns: A dictionary of whatever was in the config for the service instance"""
general_config = service_configuration_lib.read_service_configuration(
service, soa_dir=soa_dir
)
kubernetes_conf_file = "kubernetes-%s" % cluster
instance_configs = service_configuration_lib.read_extra_service_information(
service, kubernetes_conf_file, soa_dir=soa_dir
)
if instance.startswith("_"):
raise InvalidJobNameError(
f"Unable to load kubernetes job config for {service}.{instance} as instance name starts with '_'"
)
if instance not in instance_configs:
raise NoConfigurationForServiceError(
f"{instance} not found in config file {soa_dir}/{service}/{kubernetes_conf_file}.yaml."
)
general_config = deep_merge_dictionaries(
overrides=instance_configs[instance], defaults=general_config
)
branch_dict: Optional[BranchDictV2] = None
if load_deployments:
deployments_json = load_v2_deployments_json(service, soa_dir=soa_dir)
temp_instance_config = KubernetesDeploymentConfig(
service=service,
cluster=cluster,
instance=instance,
config_dict=general_config,
branch_dict=None,
soa_dir=soa_dir,
)
branch = temp_instance_config.get_branch()
deploy_group = temp_instance_config.get_deploy_group()
branch_dict = deployments_json.get_branch_dict(service, branch, deploy_group)
return KubernetesDeploymentConfig(
service=service,
cluster=cluster,
instance=instance,
config_dict=general_config,
branch_dict=branch_dict,
soa_dir=soa_dir,
)
@time_cache(ttl=5)
def load_kubernetes_service_config(
service: str,
instance: str,
cluster: str,
load_deployments: bool = True,
soa_dir: str = DEFAULT_SOA_DIR,
) -> "KubernetesDeploymentConfig":
"""Read a service instance's configuration for kubernetes.
If a branch isn't specified for a config, the 'branch' key defaults to
paasta-${cluster}.${instance}.
:param name: The service name
:param instance: The instance of the service to retrieve
:param cluster: The cluster to read the configuration for
:param load_deployments: A boolean indicating if the corresponding deployments.json for this service
should also be loaded
:param soa_dir: The SOA configuration directory to read from
:returns: A dictionary of whatever was in the config for the service instance"""
return load_kubernetes_service_config_no_cache(
service=service,
instance=instance,
cluster=cluster,
load_deployments=load_deployments,
soa_dir=soa_dir,
)
class InvalidKubernetesConfig(Exception):
def __init__(self, exception: Exception, service: str, instance: str) -> None:
super().__init__(
f"Couldn't generate config for kubernetes service: {service}.{instance}: {exception}"
)
class KubernetesDeploymentConfig(LongRunningServiceConfig):
config_dict: KubernetesDeploymentConfigDict
config_filename_prefix = "kubernetes"
def __init__(
self,
service: str,
cluster: str,
instance: str,
config_dict: KubernetesDeploymentConfigDict,
branch_dict: Optional[BranchDictV2],
soa_dir: str = DEFAULT_SOA_DIR,
) -> None:
super().__init__(
cluster=cluster,
instance=instance,
service=service,
config_dict=config_dict,
branch_dict=branch_dict,
soa_dir=soa_dir,
)
def copy(self) -> "KubernetesDeploymentConfig":
return self.__class__(
service=self.service,
instance=self.instance,
cluster=self.cluster,
config_dict=self.config_dict.copy(),
branch_dict=self.branch_dict.copy()
if self.branch_dict is not None
else None,
soa_dir=self.soa_dir,
)
def get_kubernetes_namespace(self) -> str:
return KUBERNETES_NAMESPACE
def get_cmd(self) -> Optional[List[str]]:
cmd = super(LongRunningServiceConfig, self).get_cmd()
if cmd:
if isinstance(cmd, str):
return ["sh", "-c", cmd]
elif isinstance(cmd, list):
return cmd
else:
raise ValueError("cmd should be str or list")
else:
return None
def get_bounce_method(self) -> str:
"""Get the bounce method specified in the service's kubernetes configuration."""
# map existing bounce methods to k8s equivalents.
# but if there's an EBS volume we must downthenup to free up the volume.
# in the future we may support stateful sets to dynamically create the volumes
bounce_method = self.config_dict.get("bounce_method", "crossover")
if self.get_aws_ebs_volumes() and not bounce_method == "downthenup":
raise Exception(
"If service instance defines an EBS volume it must use a downthenup bounce_method"
)
return bounce_method
def get_autoscaling_params(self) -> AutoscalingParamsDict:
default_params: AutoscalingParamsDict = {
"metrics_provider": "mesos_cpu",
"decision_policy": "proportional",
"setpoint": 0.8,
}
return deep_merge_dictionaries(
overrides=self.config_dict.get("autoscaling", AutoscalingParamsDict({})),
defaults=default_params,
)
def get_hpa_metric_spec(
self, name: str, cluster: str, namespace: str = "paasta"
) -> Optional[V2beta1HorizontalPodAutoscaler]:
hpa_config = self.config_dict["horizontal_autoscaling"]
min_replicas = hpa_config["min_replicas"]
max_replicas = hpa_config["max_replicas"]
selector = V1LabelSelector(match_labels={"kubernetes_cluster": cluster})
annotations = {"signalfx.com.custom.metrics": ""}
metrics = []
for metric_name, value in hpa_config.items():
if metric_name in {"min_replicas", "max_replicas"}:
continue
if metric_name in {"cpu", "memory"}:
metrics.append(
V2beta1MetricSpec(
type="Resource",
resource=V2beta1ResourceMetricSource(
name=metric_name,
target_average_utilization=value["target_average_value"],
),
)
)
elif metric_name in {"http", "uwsgi"}:
if "dimensions" not in value:
metrics.append(
V2beta1MetricSpec(
type="Pods",
pods=V2beta1PodsMetricSource(
metric_name=metric_name,
target_average_value=value["target_average_value"],
selector=selector,
),
)
)
else:
metrics.append(
V2beta1MetricSpec(
type="External",
external=V2beta1ExternalMetricSource(
metric_name=metric_name,
target_value=value["target_average_value"],
),
)
)
filters = " and ".join(
f'filter("{k}", "{v}")' for k, v in value["dimensions"].items()
)
annotations[
f"signalfx.com.external.metric/{metric_name}"
] = f'data("{metric_name}", filter={filters}).mean().publish()'
else:
metrics.append(
V2beta1MetricSpec(
type="External",
external=V2beta1ExternalMetricSource(
metric_name=metric_name, target_value=value["target_value"]
),
)
)
annotations[f"signalfx.com.external.metric/{metric_name}"] = value[
"signalflow_metrics_query"
]
return V2beta1HorizontalPodAutoscaler(
kind="HorizontalPodAutoscaler",
metadata=V1ObjectMeta(
name=name, namespace=namespace, annotations=annotations
),
spec=V2beta1HorizontalPodAutoscalerSpec(
max_replicas=max_replicas,
min_replicas=min_replicas,
metrics=metrics,
scale_target_ref=V2beta1CrossVersionObjectReference(
api_version="apps/v1", kind="Deployment", name=name
),
),
)
def get_autoscaling_metric_spec(
self, name: str, cluster: str, namespace: str = "paasta"
) -> Optional[V2beta1HorizontalPodAutoscaler]:
# use new autoscaling configuration if it exists.
if "horizontal_autoscaling" in self.config_dict:
return self.get_hpa_metric_spec(name, cluster, namespace)
min_replicas = self.get_min_instances()
max_replicas = self.get_max_instances()
if not min_replicas or not max_replicas:
log.error(
f"Please specify min_instances and max_instances for autoscaling to work: {min_replicas}, {max_replicas}"
)
return None
autoscaling_params = self.get_autoscaling_params()
metrics_provider = autoscaling_params["metrics_provider"]
# TODO support multiple metrics
metrics = []
target = autoscaling_params["setpoint"] * 100
annotations: Dict[str, str] = {}
# TODO support bespoke PAASTA-15680
selector = V1LabelSelector(match_labels={"kubernetes_cluster": cluster})
if autoscaling_params["decision_policy"] == "bespoke":
log.error(
f"Sorry, bespoke is not implemented yet. Please use a different decision \
policy if possible for {name}/name in namespace{namespace}"
)
return None
elif metrics_provider == "mesos_cpu":
metrics.append(
V2beta1MetricSpec(
type="Resource",
resource=V2beta1ResourceMetricSource(
name="cpu", target_average_utilization=int(target)
),
)
)
elif metrics_provider == "http":
annotations = {"signalfx.com.custom.metrics": ""}
metrics.append(
V2beta1MetricSpec(
type="Pods",
pods=V2beta1PodsMetricSource(
metric_name="http",
target_average_value=target,
selector=selector,
),
)
)
elif metrics_provider == "uwsgi":
annotations = {"signalfx.com.custom.metrics": ""}
metrics.append(
V2beta1MetricSpec(
type="Pods",
pods=V2beta1PodsMetricSource(
metric_name="uwsgi",
target_average_value=target,
selector=selector,
),
)
)
else:
log.error(
f"Wrong metrics specified: {metrics_provider} for\
{name}/name in namespace{namespace}"
)
return None
return V2beta1HorizontalPodAutoscaler(
kind="HorizontalPodAutoscaler",
metadata=V1ObjectMeta(
name=name, namespace=namespace, annotations=annotations
),
spec=V2beta1HorizontalPodAutoscalerSpec(
max_replicas=max_replicas,
min_replicas=min_replicas,
metrics=metrics,
scale_target_ref=V2beta1CrossVersionObjectReference(
api_version="apps/v1", kind="Deployment", name=name
),
),
)
def get_deployment_strategy_config(self) -> V1DeploymentStrategy:
# get soa defined bounce_method
bounce_method = self.get_bounce_method()
# get k8s equivalent
strategy_type = KUBE_DEPLOY_STATEGY_MAP[bounce_method]
if strategy_type == "RollingUpdate":
max_surge = "100%"
if bounce_method == "crossover":
max_unavailable = "{}%".format(
int((1 - self.get_bounce_margin_factor()) * 100)
)
elif bounce_method == "brutal":
# `brutal` bounce method means a bounce margin factor of 0, do not call get_bounce_margin_factor
max_unavailable = "100%"
else:
raise Exception("Unknown bounce method for RollingUpdate.")
rolling_update = V1RollingUpdateDeployment
# this translates bounce_margin to k8s speak maxUnavailable
# for now we keep max_surge 100% but we could customise later
rolling_update = V1RollingUpdateDeployment(
max_surge=max_surge, max_unavailable=max_unavailable
)
else:
rolling_update = None
return V1DeploymentStrategy(type=strategy_type, rolling_update=rolling_update)
def get_sanitised_volume_name(self, volume_name: str, length_limit: int = 0) -> str:
"""I know but we really aren't allowed many characters..."""
volume_name = volume_name.rstrip("/")
sanitised = volume_name.replace("/", "slash-").replace(".", "dot-")
sanitised_name = sanitise_kubernetes_name(sanitised)
if length_limit and len(sanitised_name) > length_limit:
sanitised_name = (
sanitised_name[0 : length_limit - 6]
+ "--"
+ hashlib.md5(sanitised_name.encode("ascii")).hexdigest()[:4]
)
return sanitised_name
def get_docker_volume_name(self, docker_volume: DockerVolume) -> str:
return self.get_sanitised_volume_name(
"host--{name}".format(name=docker_volume["hostPath"]), length_limit=63
)
def get_persistent_volume_name(self, docker_volume: PersistentVolume) -> str:
return self.get_sanitised_volume_name(
"pv--{name}".format(name=docker_volume["container_path"]), length_limit=253
)
def get_aws_ebs_volume_name(self, aws_ebs_volume: AwsEbsVolume) -> str:
return self.get_sanitised_volume_name(
"aws-ebs--{name}{partition}".format(
name=aws_ebs_volume["volume_id"],
partition=aws_ebs_volume.get("partition", ""),
)
)
def read_only_mode(self, d: VolumeWithMode) -> bool:
return d.get("mode", "RO") == "RO"
def get_sidecar_containers(
self,
system_paasta_config: SystemPaastaConfig,
service_namespace_config: ServiceNamespaceConfig,
) -> Sequence[V1Container]:
registrations = " ".join(self.get_registrations())
# s_m_j currently asserts that services are healthy in smartstack before
# continuing a bounce. this readiness check lets us achieve the same thing
readiness_probe: Optional[V1Probe]
if (
self.get_enable_nerve_readiness_check()
and service_namespace_config.is_in_smartstack()
):
readiness_probe = V1Probe(
_exec=V1ExecAction(
command=[
system_paasta_config.get_nerve_readiness_check_script(),
str(self.get_container_port()),
]
+ self.get_registrations()
),
initial_delay_seconds=10,
period_seconds=10,
)
else:
readiness_probe = None
sidecars = []
if service_namespace_config.is_in_smartstack():
sidecars.append(
V1Container(
image=system_paasta_config.get_hacheck_sidecar_image_url(),
lifecycle=V1Lifecycle(
pre_stop=V1Handler(
_exec=V1ExecAction(
command=[
"/bin/sh",
"-c",
f"/usr/bin/hadown {registrations}; sleep 31",
]
)
)
),
resources=self.get_sidecar_resource_requirements(),
name=HACHECK_POD_NAME,
env=self.get_kubernetes_environment(),
ports=[V1ContainerPort(container_port=6666)],
readiness_probe=readiness_probe,
)
)
return sidecars
def get_container_env(self) -> Sequence[V1EnvVar]:
secret_env_vars = {}
shared_secret_env_vars = {}
for k, v in self.get_env().items():
if is_secret_ref(v):
if is_shared_secret(v):
shared_secret_env_vars[k] = v
else:
secret_env_vars[k] = v
user_env = [
V1EnvVar(name=name, value=value)
for name, value in self.get_env().items()
if name
not in list(secret_env_vars.keys()) + list(shared_secret_env_vars.keys())
]
user_env += self.get_kubernetes_secret_env_vars(
secret_env_vars=secret_env_vars,
shared_secret_env_vars=shared_secret_env_vars,
)
return user_env + self.get_kubernetes_environment() # type: ignore
def get_kubernetes_secret_env_vars(
self,
secret_env_vars: Mapping[str, str],
shared_secret_env_vars: Mapping[str, str],
) -> Sequence[V1EnvVar]:
ret = []
for k, v in secret_env_vars.items():
service = self.get_sanitised_service_name()
secret = get_secret_name_from_ref(v)
sanitised_secret = sanitise_kubernetes_name(secret)
ret.append(
V1EnvVar(
name=k,
value_from=V1EnvVarSource(
secret_key_ref=V1SecretKeySelector(
name=f"paasta-secret-{service}-{sanitised_secret}",
key=secret,
optional=False,
)
),
)
)
for k, v in shared_secret_env_vars.items():
service = sanitise_kubernetes_name(SHARED_SECRET_SERVICE)
secret = get_secret_name_from_ref(v)
sanitised_secret = sanitise_kubernetes_name(secret)
ret.append(
V1EnvVar(
name=k,
value_from=V1EnvVarSource(
secret_key_ref=V1SecretKeySelector(
name=f"paasta-secret-{service}-{sanitised_secret}",
key=secret,
optional=False,
)
),
)
)
return ret
def get_kubernetes_environment(self) -> Sequence[V1EnvVar]:
kubernetes_env = [
V1EnvVar(
name="PAASTA_POD_IP",
value_from=V1EnvVarSource(
field_ref=V1ObjectFieldSelector(field_path="status.podIP")
),
),
V1EnvVar(
# this is used by some functions of operator-sdk
# it uses this environment variable to get the pods
name="POD_NAME",
value_from=V1EnvVarSource(
field_ref=V1ObjectFieldSelector(field_path="metadata.name")
),
),
V1EnvVar(
name="PAASTA_HOST",
value_from=V1EnvVarSource(
field_ref=V1ObjectFieldSelector(field_path="spec.nodeName")
),
),
]
return kubernetes_env
def get_resource_requirements(self) -> V1ResourceRequirements:
return V1ResourceRequirements(
limits={
"cpu": self.get_cpus() + self.get_cpu_burst_add(),
"memory": f"{self.get_mem()}Mi",
"ephemeral-storage": f"{self.get_disk()}Mi",
},
requests={
"cpu": self.get_cpus(),
"memory": f"{self.get_mem()}Mi",
"ephemeral-storage": f"{self.get_disk()}Mi",
},
)
def get_sidecar_resource_requirements(self) -> V1ResourceRequirements:
return V1ResourceRequirements(
limits={"cpu": 0.1, "memory": "1024Mi", "ephemeral-storage": "256Mi"},
requests={"cpu": 0.1, "memory": "1024Mi", "ephemeral-storage": "256Mi"},
)
def get_liveness_probe(
self, service_namespace_config: ServiceNamespaceConfig
) -> Optional[V1Probe]:
mode = self.get_healthcheck_mode(service_namespace_config)
if mode is None:
return None
initial_delay_seconds = self.get_healthcheck_grace_period_seconds()
period_seconds = self.get_healthcheck_interval_seconds()
timeout_seconds = self.get_healthcheck_timeout_seconds()
failure_threshold = self.get_healthcheck_max_consecutive_failures()
probe = V1Probe(
failure_threshold=failure_threshold,
initial_delay_seconds=initial_delay_seconds,
period_seconds=period_seconds,
timeout_seconds=timeout_seconds,
)
if mode == "http" or mode == "https":
path = self.get_healthcheck_uri(service_namespace_config)
probe.http_get = V1HTTPGetAction(
path=path, port=self.get_container_port(), scheme=mode.upper()
)
elif mode == "tcp":
probe.tcp_socket = V1TCPSocketAction(port=self.get_container_port())
elif mode == "cmd":
probe._exec = V1ExecAction(
command=["/bin/sh", "-c", self.get_healthcheck_cmd()]
)
else:
raise InvalidHealthcheckMode(
"Unknown mode: %s. Only acceptable healthcheck modes are http/https/tcp"
% mode
)
return probe
def get_security_context(self) -> Optional[V1SecurityContext]:
cap_add = self.config_dict.get("cap_add", None)
if cap_add is None:
return None
return V1SecurityContext(capabilities=V1Capabilities(add=cap_add))
def get_kubernetes_containers(
self,
docker_volumes: Sequence[DockerVolume],
system_paasta_config: SystemPaastaConfig,
aws_ebs_volumes: Sequence[AwsEbsVolume],
service_namespace_config: ServiceNamespaceConfig,
) -> Sequence[V1Container]:
service_container = V1Container(
image=self.get_docker_url(),
command=self.get_cmd(),
args=self.get_args(),
env=self.get_container_env(),
resources=self.get_resource_requirements(),
lifecycle=V1Lifecycle(
pre_stop=V1Handler(
_exec=V1ExecAction(command=["/bin/sh", "-c", "sleep 30"])
)
),
name=self.get_sanitised_instance_name(),
liveness_probe=self.get_liveness_probe(service_namespace_config),
ports=[V1ContainerPort(container_port=self.get_container_port())],
security_context=self.get_security_context(),
volume_mounts=self.get_volume_mounts(
docker_volumes=docker_volumes,
aws_ebs_volumes=aws_ebs_volumes,
persistent_volumes=self.get_persistent_volumes(),
),
)
containers = [service_container] + self.get_sidecar_containers( # type: ignore
system_paasta_config=system_paasta_config,
service_namespace_config=service_namespace_config,
)
return containers
def get_pod_volumes(
self,
docker_volumes: Sequence[DockerVolume],
aws_ebs_volumes: Sequence[AwsEbsVolume],
) -> Sequence[V1Volume]:
pod_volumes = []
unique_docker_volumes = {
self.get_docker_volume_name(docker_volume): docker_volume
for docker_volume in docker_volumes
}
for name, docker_volume in unique_docker_volumes.items():
pod_volumes.append(
V1Volume(
host_path=V1HostPathVolumeSource(path=docker_volume["hostPath"]),
name=name,
)
)
unique_aws_ebs_volumes = {
self.get_aws_ebs_volume_name(aws_ebs_volume): aws_ebs_volume
for aws_ebs_volume in aws_ebs_volumes
}
for name, aws_ebs_volume in unique_aws_ebs_volumes.items():
pod_volumes.append(
V1Volume(
aws_elastic_block_store=V1AWSElasticBlockStoreVolumeSource(
volume_id=aws_ebs_volume["volume_id"],
fs_type=aws_ebs_volume.get("fs_type"),
partition=aws_ebs_volume.get("partition"),
# k8s wants RW volume even if it's later mounted RO
read_only=False,
),
name=name,
)
)
return pod_volumes
def get_volume_mounts(
self,
docker_volumes: Sequence[DockerVolume],
aws_ebs_volumes: Sequence[AwsEbsVolume],
persistent_volumes: Sequence[PersistentVolume],
) -> Sequence[V1VolumeMount]:
return (
[
V1VolumeMount(
mount_path=docker_volume["containerPath"],
name=self.get_docker_volume_name(docker_volume),
read_only=self.read_only_mode(docker_volume),
)
for docker_volume in docker_volumes
]
+ [
V1VolumeMount(
mount_path=aws_ebs_volume["container_path"],
name=self.get_aws_ebs_volume_name(aws_ebs_volume),
read_only=self.read_only_mode(aws_ebs_volume),
)
for aws_ebs_volume in aws_ebs_volumes
]
+ [
V1VolumeMount(
mount_path=volume["container_path"],
name=self.get_persistent_volume_name(volume),
read_only=self.read_only_mode(volume),
)
for volume in persistent_volumes
]
)
def get_sanitised_service_name(self) -> str:
return sanitise_kubernetes_name(self.get_service())
def get_sanitised_instance_name(self) -> str:
return sanitise_kubernetes_name(self.get_instance())
def get_instances(self, with_limit: bool = True) -> int:
"""
Return expected number of instances. If the controller is running, return
desired replicas. Otherwise, return the number of instances in yelpsoa_config
"""
if self.get_max_instances() is not None:
try:
return (
KubeClient()
.deployments.read_namespaced_deployment(
name=self.get_sanitised_deployment_name(), namespace="paasta"
)
.spec.replicas
)
except ApiException as e:
log.error(e)
log.debug(
"Error occured when trying to connect to Kubernetes API, \
returning max_instances (%d)"
% self.get_max_instances()
)
return self.get_max_instances()
else:
instances = self.config_dict.get("instances", 1)
log.debug("Autoscaling not enabled, returning %d instances" % instances)
return instances
def get_desired_instances(self) -> int:
""" For now if we have an EBS instance it means we can only have 1 instance
since we can't attach to multiple instances. In the future we might support
statefulsets which are clever enough to manage EBS for you"""
if self.get_desired_state() == "start":
max_instances = self.get_max_instances()
instances = (
max_instances
if max_instances is not None
else self.config_dict.get("instances", 1)
)
elif self.get_desired_state() == "stop":
instances = 0
log.debug("Instance is set to stop. Returning '0' instances")
else:
raise Exception(f"The state of {self.service}.{self.instance} is unknown.")
if self.get_aws_ebs_volumes() and instances not in [1, 0]:
raise Exception(
"Number of instances must be 1 or 0 if an EBS volume is defined."
)
return instances
def get_volume_claim_templates(self) -> Sequence[V1PersistentVolumeClaim]:
return [
V1PersistentVolumeClaim(
metadata=V1ObjectMeta(name=self.get_persistent_volume_name(volume)),
spec=V1PersistentVolumeClaimSpec(
# must be ReadWriteOnce for EBS
access_modes=["ReadWriteOnce"],
storage_class_name=self.get_storage_class_name(volume),
resources=V1ResourceRequirements(
requests={"storage": f"{volume['size']}Gi"}
),
),
)
for volume in self.get_persistent_volumes()
]
def get_storage_class_name(self, volume: PersistentVolume) -> str:
storage_class_name = volume.get("storage_class_name", "ebs")
if storage_class_name not in ["ebs", "ebs-slow"]:
log.warning(f"storage class {storage_class_name} is not supported")
storage_class_name = "ebs"
return storage_class_name
def get_kubernetes_metadata(self, code_sha: str) -> V1ObjectMeta:
return V1ObjectMeta(