-
Notifications
You must be signed in to change notification settings - Fork 16.6k
Pass KE workload via mounted secret to workers #62129
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
amoghrajesh
wants to merge
9
commits into
apache:main
Choose a base branch
from
astronomer:pass-jwt-to-ke-pods-via-secret
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e9c2758
Pass KE workload via mounted secret to workers
amoghrajesh e7b3b5f
adding secret cleanup to cleanup-pods job
amoghrajesh b4a137b
add other labels to secret
amoghrajesh 0b3d3e9
moving mount logic to construct_pod
amoghrajesh 0cb0b19
swapping to ownerRefs
amoghrajesh 3d773ea
cleanup
amoghrajesh 0fa0a3a
simpler commits from jed
amoghrajesh c123e2c
handling comments from jed about safe deletion
amoghrajesh f4a1dc9
making error more explicit
amoghrajesh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -28,6 +28,7 @@ | |
| from urllib3.exceptions import ReadTimeoutError | ||
|
|
||
| from airflow.providers.cncf.kubernetes.backcompat import get_logical_date_key | ||
| from airflow.providers.cncf.kubernetes.exceptions import KubernetesApiPermissionError | ||
| from airflow.providers.cncf.kubernetes.executors.kubernetes_executor_types import ( | ||
| ADOPTED, | ||
| ALL_NAMESPACES, | ||
|
|
@@ -44,7 +45,12 @@ | |
| annotations_to_key, | ||
| create_unique_id, | ||
| ) | ||
| from airflow.providers.cncf.kubernetes.pod_generator import PodGenerator, workload_to_command_args | ||
| from airflow.providers.cncf.kubernetes.pod_generator import ( | ||
| WORKLOAD_SECRET_NAME_PREFIX, | ||
| PodGenerator, | ||
| make_safe_label_value, | ||
| workload_to_command_args_json_path, | ||
| ) | ||
| from airflow.providers.common.compat.sdk import AirflowException | ||
| from airflow.utils.log.logging_mixin import LoggingMixin | ||
| from airflow.utils.state import TaskInstanceState | ||
|
|
@@ -553,12 +559,50 @@ def run_next(self, next_job: KubernetesJob) -> None: | |
| pod_template_file = next_job.pod_template_file | ||
|
|
||
| dag_id, task_id, run_id, try_number, map_index = key | ||
|
|
||
| pod_id = create_unique_id(dag_id, task_id) | ||
| secret_name: str | None = None | ||
|
|
||
| if len(command) == 1: | ||
| from airflow.executors.workloads import ExecuteTask | ||
|
|
||
| if isinstance(command[0], ExecuteTask): | ||
| workload = command[0] | ||
| command = workload_to_command_args(workload) | ||
| secret_name = f"{WORKLOAD_SECRET_NAME_PREFIX}-{pod_id}" | ||
| labels: dict[str, str] = { | ||
| "airflow-workload-secret": "true", | ||
| "dag_id": make_safe_label_value(workload.ti.dag_id), | ||
| "task_id": make_safe_label_value(workload.ti.task_id), | ||
| "run_id": make_safe_label_value(workload.ti.run_id), | ||
| "try_number": str(workload.ti.try_number), | ||
| "ti_id": str(workload.ti.id), | ||
| } | ||
| if workload.ti.map_index is not None and workload.ti.map_index >= 0: | ||
| labels["map_index"] = str(workload.ti.map_index) | ||
| try: | ||
| self.kube_client.create_namespaced_secret( | ||
| namespace=self.namespace, | ||
| body=client.V1Secret( | ||
| metadata=client.V1ObjectMeta( | ||
| name=secret_name, | ||
| namespace=self.namespace, | ||
| labels=labels, | ||
| ), | ||
| string_data={"workload.json": workload.model_dump_json()}, | ||
| ), | ||
| ) | ||
| except ApiException as e: | ||
| if e.status == 403: | ||
| raise KubernetesApiPermissionError( | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seemed like the right exception to raise 🤷🏽 |
||
| f"Failed to create workload secret '{secret_name}' in namespace " | ||
| f"'{self.namespace}': permission denied (HTTP 403). " | ||
| "Ensure the RBAC pod-launcher-role has 'create' and 'patch' verbs for " | ||
| "'secrets'. If you recently upgraded the cncf-kubernetes provider, " | ||
| "update the pod-launcher-role in your helm charts or grant the missing " | ||
| "permissions manually." | ||
| ) from e | ||
| raise | ||
| command = workload_to_command_args_json_path() | ||
| else: | ||
| raise ValueError( | ||
| f"KubernetesExecutor doesn't know how to handle workload of type: {type(command[0])}" | ||
|
|
@@ -576,7 +620,7 @@ def run_next(self, next_job: KubernetesJob) -> None: | |
| pod = PodGenerator.construct_pod( | ||
| namespace=self.namespace, | ||
| scheduler_job_id=self.scheduler_job_id, | ||
| pod_id=create_unique_id(dag_id, task_id), | ||
| pod_id=pod_id, | ||
| dag_id=dag_id, | ||
| task_id=task_id, | ||
| kube_image=self.kube_config.kube_image, | ||
|
|
@@ -588,7 +632,9 @@ def run_next(self, next_job: KubernetesJob) -> None: | |
| pod_override_object=kube_executor_config, | ||
| base_worker_pod=base_worker_pod, | ||
| with_mutation_hook=True, | ||
| workload_secret_name=secret_name, | ||
| ) | ||
|
|
||
| # Reconcile the pod generated by the Operator and the Pod | ||
| # generated by the .cfg file | ||
| self.log.info( | ||
|
|
@@ -600,9 +646,58 @@ def run_next(self, next_job: KubernetesJob) -> None: | |
| self.log.debug("Kubernetes running for command %s", command) | ||
| self.log.debug("Kubernetes launching image %s", pod.spec.containers[0].image) | ||
|
|
||
| # the watcher will monitor pods, so we do not block. | ||
| self.run_pod_async(pod, **self.kube_config.kube_client_request_args) | ||
| self.log.debug("Kubernetes Job created!") | ||
| try: | ||
| resp = self.run_pod_async(pod, **self.kube_config.kube_client_request_args) | ||
| except Exception: | ||
| if secret_name: | ||
| try: | ||
| self.kube_client.delete_namespaced_secret(secret_name, self.namespace) | ||
| except ApiException: | ||
| self.log.debug( | ||
| "Failed to clean up workload secret %s after pod creation failure; " | ||
| "it will be removed by the cleanup CronJob.", | ||
| secret_name, | ||
| exc_info=True, | ||
| ) | ||
| raise | ||
|
|
||
| if secret_name: | ||
| try: | ||
| self.kube_client.patch_namespaced_secret( | ||
| name=secret_name, | ||
| namespace=self.namespace, | ||
| body={ | ||
| "metadata": { | ||
| "ownerReferences": [ | ||
| { | ||
| "apiVersion": "v1", | ||
| "kind": "Pod", | ||
| "name": resp.metadata.name, | ||
| "uid": resp.metadata.uid, | ||
| # Pod should not wait on secret to be deleted | ||
| "blockOwnerDeletion": False, | ||
| } | ||
| ] | ||
| } | ||
| }, | ||
| ) | ||
| except ApiException as e: | ||
| if e.status == 403: | ||
| self.log.warning( | ||
| "Could not set ownerReference on workload secret %s: permission denied (HTTP 403). " | ||
| "Ensure the scheduler's RBAC role grants the 'patch' verb on 'secrets'. " | ||
| "If you recently upgraded the cncf-kubernetes provider, update the " | ||
| "pod-launcher-role in your Helm chart. " | ||
| "The cleanup CronJob will delete the secret as a fallback.", | ||
| secret_name, | ||
| ) | ||
| else: | ||
| self.log.warning( | ||
| "Could not set ownerReference on workload secret %s; " | ||
| "as a fallback the cleanup CronJob will delete it.", | ||
| secret_name, | ||
| exc_info=True, | ||
| ) | ||
|
|
||
| def delete_pod(self, pod_name: str, namespace: str) -> None: | ||
| """Delete Pod from a namespace; does not raise if it does not exist.""" | ||
|
|
@@ -616,7 +711,7 @@ def delete_pod(self, pod_name: str, namespace: str) -> None: | |
| ) | ||
| except ApiException as e: | ||
| # If the pod is already deleted | ||
| if str(e.status) != "404": | ||
| if e.status != 404: | ||
| raise | ||
|
|
||
| def patch_pod_revoked(self, *, pod_name: str, namespace: str): | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.