Source code for airflow.providers.google.cloud.hooks.kubernetes_engine
## Licensed to the Apache Software Foundation (ASF) under one# or more contributor license agreements. See the NOTICE file# distributed with this work for additional information# regarding copyright ownership. The ASF licenses this file# to you 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."""This module contains a Google Kubernetes Engine Hook... spelling:word-list:: gapic enums"""from__future__importannotationsimportcontextlibimportjsonimporttimeimportwarningsfromfunctoolsimportcached_propertyfromtypingimportTYPE_CHECKING,Sequencefromgcloud.aio.authimportTokenfromgoogle.api_core.exceptionsimportNotFoundfromgoogle.api_core.gapic_v1.methodimportDEFAULT,_MethodDefaultfromgoogle.auth.transportimportrequestsasgoogle_requests# not sure why but mypy complains on missing `container_v1` but it is clearly there and is importablefromgoogle.cloudimportcontainer_v1,exceptions# type: ignore[attr-defined]fromgoogle.cloud.container_v1importClusterManagerAsyncClient,ClusterManagerClientfromgoogle.cloud.container_v1.typesimportCluster,Operationfromkubernetesimportclientfromkubernetes_asyncioimportclientasasync_clientfromkubernetes_asyncio.config.kube_configimportFileOrDatafromurllib3.exceptionsimportHTTPErrorfromairflowimportversionfromairflow.exceptionsimportAirflowException,AirflowProviderDeprecationWarningfromairflow.providers.cncf.kubernetes.utils.pod_managerimportPodOperatorHookProtocolfromairflow.providers.google.common.constsimportCLIENT_INFOfromairflow.providers.google.common.hooks.base_googleimport(PROVIDE_PROJECT_ID,GoogleBaseAsyncHook,GoogleBaseHook,)ifTYPE_CHECKING:importgoogle.auth.credentialsfromgoogle.api_core.retryimportRetryfromkubernetes_asyncio.client.modelsimportV1Pod
[docs]classGKEHook(GoogleBaseHook):"""Google Kubernetes Engine cluster APIs. All the methods in the hook where project_id is used must be called with keyword arguments rather than positional. """def__init__(self,gcp_conn_id:str="google_cloud_default",location:str|None=None,impersonation_chain:str|Sequence[str]|None=None,**kwargs,)->None:ifkwargs.get("delegate_to")isnotNone:raiseRuntimeError("The `delegate_to` parameter has been deprecated before and finally removed in this version"" of Google Provider. You MUST convert it to `impersonate_chain`")super().__init__(gcp_conn_id=gcp_conn_id,impersonation_chain=impersonation_chain,)self._client:ClusterManagerClient|None=Noneself.location=location
[docs]defget_cluster_manager_client(self)->ClusterManagerClient:"""Create or get a ClusterManagerClient."""ifself._clientisNone:self._client=ClusterManagerClient(credentials=self.get_credentials(),client_info=CLIENT_INFO)returnself._client
# To preserve backward compatibility# TODO: remove one day
[docs]defget_conn(self)->container_v1.ClusterManagerClient:warnings.warn("The get_conn method has been deprecated. You should use the get_cluster_manager_client method.",AirflowProviderDeprecationWarning,)returnself.get_cluster_manager_client()
# To preserve backward compatibility# TODO: remove one day
[docs]defget_client(self)->ClusterManagerClient:warnings.warn("The get_client method has been deprecated. You should use the get_conn method.",AirflowProviderDeprecationWarning,)returnself.get_conn()
[docs]defwait_for_operation(self,operation:Operation,project_id:str|None=None)->Operation:"""Continuously fetch the status from Google Cloud. This is done until the given operation completes, or raises an error. :param operation: The Operation to wait for. :param project_id: Google Cloud project ID. :return: A new, updated operation fetched from Google Cloud. """self.log.info("Waiting for OPERATION_NAME %s",operation.name)time.sleep(OPERATIONAL_POLL_INTERVAL)whileoperation.status!=Operation.Status.DONE:ifoperation.statusin(Operation.Status.RUNNING,Operation.Status.PENDING):time.sleep(OPERATIONAL_POLL_INTERVAL)else:raiseexceptions.GoogleCloudError(f"Operation has failed with status: {operation.status}")# To update status of operationoperation=self.get_operation(operation.name,project_id=project_idorself.project_id)returnoperation
[docs]defget_operation(self,operation_name:str,project_id:str|None=None)->Operation:"""Get an operation from Google Cloud. :param operation_name: Name of operation to fetch :param project_id: Google Cloud project ID :return: The new, updated operation from Google Cloud """returnself.get_cluster_manager_client().get_operation(name=(f"projects/{project_idorself.project_id}"f"/locations/{self.location}/operations/{operation_name}"))
@staticmethoddef_append_label(cluster_proto:Cluster,key:str,val:str)->Cluster:"""Append labels to provided Cluster Protobuf. Labels must fit the regex ``[a-z]([-a-z0-9]*[a-z0-9])?`` (current airflow version string follows semantic versioning spec: x.y.z). :param cluster_proto: The proto to append resource_label airflow version to :param key: The key label :param val: :return: The cluster proto updated with new label """val=val.replace(".","-").replace("+","-")cluster_proto.resource_labels.update({key:val})returncluster_proto@GoogleBaseHook.fallback_to_default_project_id
[docs]defdelete_cluster(self,name:str,project_id:str=PROVIDE_PROJECT_ID,wait_to_complete:bool=True,retry:Retry|_MethodDefault=DEFAULT,timeout:float|None=None,)->Operation|None:"""Deletes the cluster, the Kubernetes endpoint, and all worker nodes. Firewalls and routes that were configured during cluster creation are also deleted. Other Google Compute Engine resources that might be in use by the cluster (e.g. load balancer resources) will not be deleted if they were not present at the initial create time. :param name: The name of the cluster to delete. :param project_id: Google Cloud project ID. :param wait_to_complete: If *True*, wait until the deletion is finished before returning. :param retry: Retry object used to determine when/if to retry requests. If None is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if retry is specified, the timeout applies to each individual attempt. :return: The full url to the delete operation if successful, else None. """self.log.info("Deleting (project_id=%s, location=%s, cluster_id=%s)",project_id,self.location,name)try:operation=self.get_cluster_manager_client().delete_cluster(name=f"projects/{project_id}/locations/{self.location}/clusters/{name}",retry=retry,timeout=timeout,)ifwait_to_complete:operation=self.wait_for_operation(operation,project_id)# Returns server-defined url for the resourcereturnoperationexceptNotFoundaserror:self.log.info("Assuming Success: %s",error.message)returnNone
@GoogleBaseHook.fallback_to_default_project_id
[docs]defcreate_cluster(self,cluster:dict|Cluster,project_id:str=PROVIDE_PROJECT_ID,wait_to_complete:bool=True,retry:Retry|_MethodDefault=DEFAULT,timeout:float|None=None,)->Operation|Cluster:"""Create a cluster. This should consist of the specified number, and the type of Google Compute Engine instances. :param cluster: A Cluster protobuf or dict. If dict is provided, it must be of the same form as the protobuf message :class:`google.cloud.container_v1.types.Cluster`. :param project_id: Google Cloud project ID. :param wait_to_complete: A boolean value which makes method to sleep while operation of creation is not finished. :param retry: A retry object (``google.api_core.retry.Retry``) used to retry requests. If None is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if retry is specified, the timeout applies to each individual attempt. :return: The full url to the new, or existing, cluster. :raises ParseError: On JSON parsing problems when trying to convert dict. :raises AirflowException: cluster is not dict type nor Cluster proto type. """ifisinstance(cluster,dict):cluster=Cluster.from_json(json.dumps(cluster))elifnotisinstance(cluster,Cluster):raiseAirflowException("cluster is not instance of Cluster proto or python dict")self._append_label(cluster,"airflow-version","v"+version.version)# type: ignoreself.log.info("Creating (project_id=%s, location=%s, cluster_name=%s)",project_id,self.location,cluster.name,# type: ignore)operation=self.get_cluster_manager_client().create_cluster(parent=f"projects/{project_id}/locations/{self.location}",cluster=cluster,# type: ignoreretry=retry,timeout=timeout,)ifwait_to_complete:operation=self.wait_for_operation(operation,project_id)returnoperation
@GoogleBaseHook.fallback_to_default_project_id
[docs]defget_cluster(self,name:str,project_id:str=PROVIDE_PROJECT_ID,retry:Retry|_MethodDefault=DEFAULT,timeout:float|None=None,)->Cluster:"""Get details of specified cluster. :param name: The name of the cluster to retrieve. :param project_id: Google Cloud project ID. :param retry: A retry object used to retry requests. If None is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if retry is specified, the timeout applies to each individual attempt. """self.log.info("Fetching cluster (project_id=%s, location=%s, cluster_name=%s)",project_idorself.project_id,self.location,name,)returnself.get_cluster_manager_client().get_cluster(name=f"projects/{project_id}/locations/{self.location}/clusters/{name}",retry=retry,timeout=timeout,)
[docs]classGKEAsyncHook(GoogleBaseAsyncHook):"""Asynchronous client of GKE."""
[docs]asyncdefget_operation(self,operation_name:str,project_id:str=PROVIDE_PROJECT_ID,)->Operation:"""Fetch an operation from Google Cloud. :param operation_name: Name of operation to fetch. :param project_id: Google Cloud project ID. :return: The new, updated operation from Google Cloud. """project_id=project_idor(awaitself.get_sync_hook()).project_idoperation_path=f"projects/{project_id}/locations/{self.location}/operations/{operation_name}"client=awaitself._get_client()returnawaitclient.get_operation(name=operation_path,)
[docs]classGKEPodHook(GoogleBaseHook,PodOperatorHookProtocol):"""Google Kubernetes Engine pod APIs."""def__init__(self,cluster_url:str,ssl_ca_cert:str,*args,**kwargs,):super().__init__(*args,**kwargs)self._cluster_url=cluster_urlself._ssl_ca_cert=ssl_ca_cert@cached_property
[docs]defget_namespace(self):"""Get the namespace configured by the Airflow connection."""
def_get_namespace(self):"""For compatibility with KubernetesHook. Deprecated; do not use."""
[docs]defget_xcom_sidecar_container_image(self):"""Get the xcom sidecar image defined in the connection. Implemented for compatibility with KubernetesHook. """
[docs]defget_xcom_sidecar_container_resources(self):"""Get the xcom sidecar resources defined in the connection. Implemented for compatibility with KubernetesHook. """
[docs]defget_pod(self,name:str,namespace:str)->V1Pod:"""Get a pod object. :param name: Name of the pod. :param namespace: Name of the pod's namespace. """returnself.core_v1_client.read_namespaced_pod(name=name,namespace=namespace,)
[docs]classGKEPodAsyncHook(GoogleBaseAsyncHook):"""Google Kubernetes Engine pods APIs asynchronously. :param cluster_url: The URL pointed to the cluster. :param ssl_ca_cert: SSL certificate used for authentication to the pod. """
[docs]asyncdefget_pod(self,name:str,namespace:str)->V1Pod:"""Get a pod object. :param name: Name of the pod. :param namespace: Name of the pod's namespace. """asyncwithToken(scopes=self.scopes)astoken:asyncwithself.get_conn(token)asconnection:v1_api=async_client.CoreV1Api(connection)pod:V1Pod=awaitv1_api.read_namespaced_pod(name=name,namespace=namespace,)returnpod
[docs]asyncdefdelete_pod(self,name:str,namespace:str):"""Delete a pod. :param name: Name of the pod. :param namespace: Name of the pod's namespace. """asyncwithToken(scopes=self.scopes)astoken,self.get_conn(token)asconnection:try:v1_api=async_client.CoreV1Api(connection)awaitv1_api.delete_namespaced_pod(name=name,namespace=namespace,body=client.V1DeleteOptions(),)exceptasync_client.ApiExceptionase:# If the pod is already deletedife.status!=404:raise
[docs]asyncdefread_logs(self,name:str,namespace:str):"""Read logs inside the pod while starting containers inside. All the logs will be outputted with its timestamp to track the logs after the execution of the pod is completed. The method is used for async output of the logs only in the pod failed it execution or the task was cancelled by the user. :param name: Name of the pod. :param namespace: Name of the pod's namespace. """asyncwithToken(scopes=self.scopes)astoken,self.get_conn(token)asconnection:try:v1_api=async_client.CoreV1Api(connection)logs=awaitv1_api.read_namespaced_pod_log(name=name,namespace=namespace,follow=False,timestamps=True,)logs=logs.splitlines()forlineinlogs:self.log.info("Container logs from %s",line)returnlogsexceptHTTPError:self.log.exception("There was an error reading the kubernetes API.")raise