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."""from__future__importannotationsimportcontextlibimportjsonimporttimefromcollections.abcimportSequencefromtypingimportTYPE_CHECKING,Anyfromkubernetesimportclientfromkubernetes_asyncioimportclientasasync_clientfromkubernetes_asyncio.config.kube_configimportFileOrDatafromairflowimportversionfromairflow.exceptionsimportAirflowExceptionfromairflow.providers.cncf.kubernetes.hooks.kubernetesimportAsyncKubernetesHook,KubernetesHookfromairflow.providers.cncf.kubernetes.kube_clientimport_enable_tcp_keepalivefromairflow.providers.google.common.constsimportCLIENT_INFOfromairflow.providers.google.common.hooks.base_googleimport(PROVIDE_PROJECT_ID,GoogleBaseAsyncHook,GoogleBaseHook,)fromgoogle.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.cloudimportexceptions# type: ignore[attr-defined]fromgoogle.cloud.container_v1importClusterManagerAsyncClient,ClusterManagerClientfromgoogle.cloud.container_v1.typesimportCluster,OperationifTYPE_CHECKING:importgoogle.auth.credentialsfromgoogle.api_core.retryimportRetry
[docs]classGKEClusterConnection:"""Helper for establishing connection to GKE cluster."""def__init__(self,cluster_url:str,ssl_ca_cert:str,credentials:google.auth.credentials.Credentials,enable_tcp_keepalive:bool=False,):self._cluster_url=cluster_urlself._ssl_ca_cert=ssl_ca_certself._credentials=credentials
[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:super().__init__(gcp_conn_id=gcp_conn_id,impersonation_chain=impersonation_chain,**kwargs,)self._client:ClusterManagerClient|None=None
[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
[docs]defwait_for_operation(self,operation:Operation,project_id:str=PROVIDE_PROJECT_ID)->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=PROVIDE_PROJECT_ID)->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:""" Delete 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]defcheck_cluster_autoscaling_ability(self,cluster:Cluster|dict):""" Check if the specified Cluster has ability to autoscale. Cluster should be Autopilot, with Node Auto-provisioning or regular auto-scaled node pools. Returns True if the Cluster supports autoscaling, otherwise returns False. :param cluster: The Cluster object. """ifisinstance(cluster,Cluster):cluster_dict_representation=Cluster.to_dict(cluster)elifnotisinstance(cluster,dict):raiseAirflowException("cluster is not instance of Cluster proto or python dict")else:cluster_dict_representation=clusternode_pools_autoscaled=Falsefornode_poolincluster_dict_representation["node_pools"]:try:ifnode_pool["autoscaling"]["enabled"]isTrue:node_pools_autoscaled=TruebreakexceptKeyError:self.log.info("No autoscaling enabled in Node pools level.")breakif(cluster_dict_representation["autopilot"]["enabled"]orcluster_dict_representation["autoscaling"]["enable_node_autoprovisioning"]ornode_pools_autoscaled):returnTrueelse:returnFalse
[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]classGKEKubernetesHook(GoogleBaseHook,KubernetesHook):""" GKE authenticated hook for standard Kubernetes API. This hook provides full set of the standard Kubernetes API provided by the KubernetesHook, and at the same time it provides a GKE authentication, so it makes it possible to KubernetesHook functionality against GKE clusters. """def__init__(self,cluster_url:str,ssl_ca_cert:str,enable_tcp_keepalive:bool=False,*args,**kwargs,):super().__init__(*args,**kwargs)self._cluster_url=cluster_urlself._ssl_ca_cert=ssl_ca_cert
[docs]defapply_from_yaml_file(self,api_client:Any=None,yaml_file:str|None=None,yaml_objects:list[dict]|None=None,verbose:bool=False,namespace:str="default",):""" Perform an action from a yaml file. :param api_client: A Kubernetes client application. :param yaml_file: Contains the path to yaml file. :param yaml_objects: List of YAML objects; used instead of reading the yaml_file. :param verbose: If True, print confirmation from create action. Default is False. :param namespace: Contains the namespace to create all resources inside. The namespace must preexist otherwise the resource creation will fail. """super().apply_from_yaml_file(api_client=api_clientorself.get_conn(),yaml_file=yaml_file,yaml_objects=yaml_objects,verbose=verbose,namespace=namespace,)
[docs]classGKEKubernetesAsyncHook(GoogleBaseAsyncHook,AsyncKubernetesHook):""" Async GKE authenticated hook for standard Kubernetes API. This hook provides full set of the standard Kubernetes API provided by the AsyncKubernetesHook, and at the same time it provides a GKE authentication, so it makes it possible to KubernetesHook functionality against GKE clusters. """