Skip to content

Commit 41db7ba

Browse files
K8s Ruff rules v2 (#7054)
1 parent baf4365 commit 41db7ba

5 files changed

Lines changed: 54 additions & 32 deletions

File tree

‎pyproject.toml‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -240,12 +240,6 @@ ignore = [
240240
"utils/build/*" = ["ALL"] # mostly python weblog code. it may be a good idea to enable rules here
241241

242242
"utils/{k8s_lib_injection/*,_context/_scenarios/k8s_lib_injection.py}" = [
243-
"DTZ005", # call-datetime-now-without-tzinfo: TODO
244-
"E401", # multiple-imports-on-one-line: TODO
245-
"E501", # line-too-long: TODO
246-
"E712", # true-false-comparison: TODO
247-
"F541", # f-string-missing-placeholders: TODO
248-
"FBT002", # boolean-default-value-positional-argument: TODO
249243
"RET505", # superfluous-else-return: TODO
250244
"RET508", # superfluous-else-break: TODO
251245
"RUF059", # unused-unpacked-variable: TODO

‎utils/k8s_lib_injection/k8s_cluster_provider.py‎

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,10 @@ def destroy_cluster(self) -> None:
116116

117117
def create_spak_service_account(self) -> None:
118118
"""Create service account for launching spark application in k8s"""
119-
execute_command(f"kubectl create serviceaccount spark --namespace=default")
119+
execute_command("kubectl create serviceaccount spark --namespace=default")
120120
execute_command(
121-
f"kubectl create clusterrolebinding spark-role --clusterrole=edit --serviceaccount=default:spark --namespace=default"
121+
"kubectl create clusterrolebinding spark-role --clusterrole=edit "
122+
"--serviceaccount=default:spark --namespace=default"
122123
)
123124
if PrivateRegistryConfig.is_configured():
124125
execute_command(
@@ -161,7 +162,8 @@ def _create_secret_to_access_to_internal_registry(self):
161162

162163
# Patch the default service account to use the secret
163164
execute_command(
164-
'kubectl patch serviceaccount default -p \'{"imagePullSecrets": [{"name": "private-registry-secret"}]}\' '
165+
"kubectl patch serviceaccount default "
166+
'-p \'{"imagePullSecrets": [{"name": "private-registry-secret"}]}\' '
165167
"--namespace=default"
166168
)
167169
logger.info("Successfully patched default service account")
@@ -271,7 +273,8 @@ def configure_cluster_api_connection(self) -> None:
271273
"""Configure the k8s cluster api connection"""
272274
try:
273275
# Update context name
274-
# Current context name is like: "arn:aws:eks:us-east-1:601427279990:cluster/lib-injection-testing-eks-sandbox"
276+
# Current context name is like:
277+
# "arn:aws:eks:us-east-1:601427279990:cluster/lib-injection-testing-eks-sandbox"
275278
# I only take "lib-injection-testing-eks-sandbox"
276279
arn, cluster_context = execute_command("kubectl config current-context").split("/")
277280
current_context_name = cluster_context.strip()
@@ -290,7 +293,8 @@ def configure_cluster_api_connection(self) -> None:
290293
).strip()
291294
logger.info("Configuring k8s cluster api connection, for cluster: " + self._cluster_info.cluster_name)
292295

293-
# We need to external IP to access to the test agent and the weblog (You should open manually the ports 8126 and 18080 in the aws security group before)
296+
# We need to external IP to access to the test agent and the weblog
297+
# (You should open manually the ports 8126 and 18080 in the aws security group before)
294298
self._cluster_info.cluster_host_name = execute_command(
295299
"kubectl get nodes --output jsonpath=\"{.items[0].status.addresses[?(@.type=='ExternalIP')].address}\""
296300
)
@@ -315,7 +319,7 @@ def configure_cluster_api_connection(self) -> None:
315319
configuration.assert_hostname = True
316320
configuration.verify_ssl = False
317321
client.Configuration.set_default(configuration)
318-
logger.info(f"kube config loaded")
322+
logger.info("kube config loaded")
319323

320324
except Exception as e:
321325
logger.error(f"Error loading kube config: {e}")
@@ -328,7 +332,8 @@ def execute_piped_command(self, command: str) -> str:
328332
return res.decode("utf-8").strip()
329333

330334
def get_token(self, cluster_name: str) -> str:
331-
# From cluster name like: "lib-injection-testing-eks-sandbox.us-east-1.eksctl.io" I only take "lib-injection-testing-eks-sandbox"
335+
# From cluster name like: "lib-injection-testing-eks-sandbox.us-east-1.eksctl.io"
336+
# I only take "lib-injection-testing-eks-sandbox"
332337
cluster_min_name = cluster_name.split(".")[0]
333338
token = execute_command(f"aws-iam-authenticator token -i {cluster_min_name} --token-only")
334339
return token.strip()
@@ -362,7 +367,13 @@ def configure_networking(self) -> None:
362367

363368
def ensure_cluster(self) -> None:
364369
logger.info("Ensuring kind cluster")
365-
kind_command = f"kind create cluster --image=kindest/node:v1.25.3@sha256:f52781bc0d7a19fb6c405c2af83abfeb311f130707a0e219175677e366cc45d1 --name {self.get_cluster_info().cluster_name} --config {self.get_cluster_info().cluster_template} --wait 1m"
370+
kind_command = (
371+
"kind create cluster "
372+
"--image=kindest/node:v1.25.3"
373+
"@sha256:f52781bc0d7a19fb6c405c2af83abfeb311f130707a0e219175677e366cc45d1 "
374+
f"--name {self.get_cluster_info().cluster_name} "
375+
f"--config {self.get_cluster_info().cluster_template} --wait 1m"
376+
)
366377

367378
if "GITLAB_CI" in os.environ:
368379
# Kind needs to run in bridge network to communicate with the internet: https://github.com/DataDog/buildenv/blob/master/cookbooks/dd_firewall/templates/rules.erb#L96
@@ -393,26 +404,33 @@ def _setup_kind_in_gitlab(self) -> None:
393404
# - Docker commands are forwarded to the host.
394405
# - The kind container is a sibling to the build container
395406
# Three things need to happen
396-
# 1) The kind container needs to be in the bridge network to communicate with the internet: done in _ensure_cluster()
407+
# 1) The kind container needs to be in the bridge network to communicate with the internet:
408+
# done in _ensure_cluster()
397409
# 2) Kube config needs to be altered to use the correct IP of the control plane server
398-
# 3) The internal ports needs to be used rather than external ports: handled in get_agent_port() and get_weblog_port()
410+
# 3) The internal ports needs to be used rather than external ports:
411+
# handled in get_agent_port() and get_weblog_port()
412+
control_plane_container = f"{self.get_cluster_info().cluster_name}-control-plane"
399413
correct_control_plane_ip = execute_command(
400-
f"docker container inspect {self.get_cluster_info().cluster_name}-control-plane --format '{{{{.NetworkSettings.Networks.bridge.IPAddress}}}}'"
414+
f"docker container inspect {control_plane_container} "
415+
"--format '{{.NetworkSettings.Networks.bridge.IPAddress}}'"
401416
).strip()
402417
if not correct_control_plane_ip:
403418
raise Exception("Unable to find correct control plane IP")
404419
logger.debug(f"[setup_kind_in_gitlab] correct_control_plane_ip: {correct_control_plane_ip}")
405420

406421
control_plane_address_in_config = execute_command(
407-
f'docker container inspect {self.get_cluster_info().cluster_name}-control-plane --format \'{{{{index .NetworkSettings.Ports "6443/tcp" 0 "HostIp"}}}}:{{{{index .NetworkSettings.Ports "6443/tcp" 0 "HostPort"}}}}\''
422+
f"docker container inspect {control_plane_container} "
423+
'--format \'{{index .NetworkSettings.Ports "6443/tcp" 0 "HostIp"}}'
424+
':{{index .NetworkSettings.Ports "6443/tcp" 0 "HostPort"}}\''
408425
).strip()
409426
if not control_plane_address_in_config:
410427
raise Exception("Unable to find control plane address from config")
411428
logger.debug(f"[setup_kind_in_gitlab] control_plane_address_in_config: {control_plane_address_in_config}")
412429

413430
# Replace server config with dns name + internal port
431+
kube_config_path = f"{os.environ['HOME']}/.kube/config"
414432
execute_command(
415-
f"sed -i -e 's/{control_plane_address_in_config}/{correct_control_plane_ip}:6443/g' {os.environ['HOME']}/.kube/config"
433+
f"sed -i -e 's/{control_plane_address_in_config}/{correct_control_plane_ip}:6443/g' {kube_config_path}"
416434
)
417435

418436
self.get_cluster_info().cluster_host_name = correct_control_plane_ip

‎utils/k8s_lib_injection/k8s_command_utils.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
import subprocess, os, shlex
1+
import subprocess
2+
import os
3+
import shlex
24
from typing import TYPE_CHECKING
35
from utils._logger import logger
46
from retry import retry
@@ -83,7 +85,7 @@ def helm_add_repo(name: str, url: str, k8s_cluster_info: "K8sClusterInfo", *, up
8385
logger.info(f"Adding helm repo {name} with url {url} for cluster {k8s_cluster_info.cluster_name}")
8486
execute_command(f"helm repo add {name} {url}")
8587
if update:
86-
execute_command(f"helm repo update")
88+
execute_command("helm repo update")
8789

8890

8991
@retry(delay=1, tries=5)

‎utils/k8s_lib_injection/k8s_datadog_kubernetes.py‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,10 @@ def deploy_datadog_cluster_agent(self, host_log_folder: str, namespace: str = "d
169169
"""Installs the Datadog Cluster Agent via helm for manual library injection testing.
170170
We enable the admission controller and wait for the datdog cluster to be ready.
171171
The Datadog Admission Controller is an important piece of the Datadog Cluster Agent.
172-
The main benefit of the Datadog Admission Controller is to simplify your life when it comes to configure your application Pods.
173-
Datadog Admission Controller is a Mutating Admission Controller type because it mutates, or changes, the pods configurations.
172+
The main benefit of the Datadog Admission Controller is to simplify your life when it comes to
173+
configure your application Pods.
174+
Datadog Admission Controller is a Mutating Admission Controller type because it mutates,
175+
or changes, the pods configurations.
174176
"""
175177

176178
logger.info("[Deploy datadog cluster] Deploying Datadog Cluster Agent with Admission Controler")
@@ -212,9 +214,10 @@ def deploy_datadog_cluster_agent(self, host_log_folder: str, namespace: str = "d
212214
self._wait_for_cluster_agent_ready(namespace)
213215

214216
def deploy_datadog_operator(self, host_log_folder: str, namespace: str = "datadog") -> None:
215-
"""Datadog Operator is a Kubernetes Operator that enables you to deploy and configure the Datadog Agent in a Kubernetes environment.
216-
By using the Datadog Operator, you can use a single Custom Resource Definition (CRD) to deploy the node-based Agent,
217-
the Datadog Cluster Agent, and Cluster check runners.
217+
"""Datadog Operator is a Kubernetes Operator that enables you to deploy and configure the Datadog
218+
Agent in a Kubernetes environment.
219+
By using the Datadog Operator, you can use a single Custom Resource Definition (CRD) to deploy
220+
the node-based Agent, the Datadog Cluster Agent, and Cluster check runners.
218221
"""
219222
logger.info("[Deploy datadog operator] Configuring helm repository")
220223

@@ -237,7 +240,10 @@ def deploy_datadog_operator(self, host_log_folder: str, namespace: str = "datado
237240
logger.info("[Deploy datadog operator] the operator is ready")
238241
logger.info("[Deploy datadog operator] Create the operator secrets")
239242
execute_command(
240-
f"kubectl create secret generic datadog-secret --from-literal api-key={self.api_key} --from-literal app-key={self.app_key} --namespace={namespace}"
243+
"kubectl create secret generic datadog-secret "
244+
f"--from-literal api-key={self.api_key} "
245+
f"--from-literal app-key={self.app_key} "
246+
f"--namespace={namespace}"
241247
)
242248
# Configure cluster agent image on the operator file
243249
operator_config_file = add_cluster_agent_img_operator_yaml(self.dd_cluster_img, self.output_folder)
@@ -257,11 +263,11 @@ def wait_for_test_agent(self, namespace: str) -> None:
257263
name="datadog", namespace=namespace
258264
)
259265
if daemonset_status is not None and daemonset_status.status.number_ready > 0:
260-
logger.info(f"[Test agent] daemonset status datadog running!")
266+
logger.info("[Test agent] daemonset status datadog running!")
261267
daemonset_created = True
262268
break
263269
elif daemonset_status is None:
264-
logger.info(f"[Test agent] daemonset status datadog not found")
270+
logger.info("[Test agent] daemonset status datadog not found")
265271
time.sleep(5)
266272

267273
if not daemonset_created:
@@ -308,7 +314,7 @@ def _wait_for_cluster_agent_ready(self, namespace: str, label_selector: str = "a
308314
if (
309315
cluster_agent_status
310316
and cluster_agent_status.status.phase == "Running"
311-
and cluster_agent_status.status.container_statuses[0].ready == True
317+
and cluster_agent_status.status.container_statuses[0].ready is True
312318
):
313319
logger.info("[sattus cluster agent] Cluster agent datadog running!")
314320
cluster_agent_ready = True
@@ -327,7 +333,8 @@ def _wait_for_cluster_agent_ready(self, namespace: str, label_selector: str = "a
327333
logger.error(f"Cluster agent logs: {cluster_agent_logs}")
328334
raise Exception("Cluster agent not created")
329335
# At this point the cluster_agent should be ready, we are going to wait a little bit more
330-
# to make sure the cluster_agent is ready (some times the cluster_agent is ready but the cluster agent is not ready yet)
336+
# to make sure the cluster_agent is ready (some times the cluster_agent is ready but the
337+
# cluster agent is not ready yet)
331338
time.sleep(5)
332339

333340
def export_debug_info(self, namespace: str) -> None:

‎utils/k8s_lib_injection/k8s_weblog.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@ def _get_base_weblog_pod(self):
5555
"""
5656

5757
logger.info(
58-
"[Deploy weblog] Creating weblog pod configuration. weblog_variant_image: [%s], library: [%s], library_init_image: [%s]"
58+
"[Deploy weblog] Creating weblog pod configuration. "
59+
"weblog_variant_image: [%s], library: [%s], library_init_image: [%s]"
5960
% (self.app_image, self.library, self.library_init_image)
6061
)
6162
library_lib = "js" if self.library == "nodejs" else self.library

0 commit comments

Comments
 (0)