Source code for airflow.providers.google.cloud.triggers.dataproc
## 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 Google Dataproc triggers."""from__future__importannotationsimportasyncioimportreimporttimefromtypingimportTYPE_CHECKING,Any,AsyncIterator,Sequencefromgoogle.api_core.exceptionsimportNotFoundfromgoogle.cloud.dataproc_v1importBatch,Cluster,ClusterStatus,JobStatusfromairflow.exceptionsimportAirflowExceptionfromairflow.models.taskinstanceimportTaskInstancefromairflow.providers.google.cloud.hooks.dataprocimportDataprocAsyncHook,DataprocHookfromairflow.providers.google.cloud.utils.dataprocimportDataprocOperationTypefromairflow.providers.google.common.hooks.base_googleimportPROVIDE_PROJECT_IDfromairflow.triggers.baseimportBaseTrigger,TriggerEventfromairflow.utils.sessionimportprovide_sessionfromairflow.utils.stateimportTaskInstanceStateifTYPE_CHECKING:fromsqlalchemy.orm.sessionimportSession
[docs]classDataprocBaseTrigger(BaseTrigger):"""Base class for Dataproc triggers."""def__init__(self,region:str,project_id:str=PROVIDE_PROJECT_ID,gcp_conn_id:str="google_cloud_default",impersonation_chain:str|Sequence[str]|None=None,polling_interval_seconds:int=30,cancel_on_kill:bool=True,delete_on_error:bool=True,):super().__init__()self.region=regionself.project_id=project_idself.gcp_conn_id=gcp_conn_idself.impersonation_chain=impersonation_chainself.polling_interval_seconds=polling_interval_secondsself.cancel_on_kill=cancel_on_killself.delete_on_error=delete_on_error
[docs]defget_sync_hook(self):# The synchronous hook is utilized to delete the cluster when a task is cancelled.# This is because the asynchronous hook deletion is not awaited when the trigger task# is cancelled. The call for deleting the cluster or job through the sync hook is not a blocking# call, which means it does not wait until the cluster or job is deleted.returnDataprocHook(gcp_conn_id=self.gcp_conn_id,impersonation_chain=self.impersonation_chain,)
[docs]classDataprocSubmitTrigger(DataprocBaseTrigger):""" DataprocSubmitTrigger run on the trigger worker to perform create Build operation. :param job_id: The ID of a Dataproc job. :param project_id: Google Cloud Project where the job is running :param region: The Cloud Dataproc region in which to handle the request. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param polling_interval_seconds: polling period in seconds to check for the status """def__init__(self,job_id:str,**kwargs):self.job_id=job_idsuper().__init__(**kwargs)
[docs]defget_task_instance(self,session:Session)->TaskInstance:""" Get the task instance for the current task. :param session: Sqlalchemy session """query=session.query(TaskInstance).filter(TaskInstance.dag_id==self.task_instance.dag_id,TaskInstance.task_id==self.task_instance.task_id,TaskInstance.run_id==self.task_instance.run_id,TaskInstance.map_index==self.task_instance.map_index,)task_instance=query.one_or_none()iftask_instanceisNone:raiseAirflowException("TaskInstance with dag_id: %s,task_id: %s, run_id: %s and map_index: %s is not found",self.task_instance.dag_id,self.task_instance.task_id,self.task_instance.run_id,self.task_instance.map_index,)returntask_instance
[docs]defsafe_to_cancel(self)->bool:""" Whether it is safe to cancel the external job which is being executed by this trigger. This is to avoid the case that `asyncio.CancelledError` is called because the trigger itself is stopped. Because in those cases, we should NOT cancel the external job. """# Database query is needed to get the latest state of the task instance.task_instance=self.get_task_instance()# type: ignore[call-arg]returntask_instance.state!=TaskInstanceState.DEFERRED
[docs]asyncdefrun(self):try:whileTrue:job=awaitself.get_async_hook().get_job(project_id=self.project_id,region=self.region,job_id=self.job_id)state=job.status.stateself.log.info("Dataproc job: %s is in state: %s",self.job_id,state)ifstatein(JobStatus.State.DONE,JobStatus.State.CANCELLED,JobStatus.State.ERROR):breakawaitasyncio.sleep(self.polling_interval_seconds)yieldTriggerEvent({"job_id":self.job_id,"job_state":state,"job":job})exceptasyncio.CancelledError:self.log.info("Task got cancelled.")try:ifself.job_idandself.cancel_on_killandself.safe_to_cancel():self.log.info("Cancelling the job as it is safe to do so. Note that the airflow TaskInstance is not"" in deferred state.")self.log.info("Cancelling the job: %s",self.job_id)# The synchronous hook is utilized to delete the cluster when a task is cancelled. This# is because the asynchronous hook deletion is not awaited when the trigger task is# cancelled. The call for deleting the cluster or job through the sync hook is not a# blocking call, which means it does not wait until the cluster or job is deleted.self.get_sync_hook().cancel_job(job_id=self.job_id,project_id=self.project_id,region=self.region)self.log.info("Job: %s is cancelled",self.job_id)yieldTriggerEvent({"job_id":self.job_id,"job_state":ClusterStatus.State.DELETING})exceptExceptionase:self.log.error("Failed to cancel the job: %s with error : %s",self.job_id,str(e))raisee
[docs]classDataprocClusterTrigger(DataprocBaseTrigger):""" DataprocClusterTrigger run on the trigger worker to perform create Build operation. :param cluster_name: The name of the cluster. :param project_id: Google Cloud Project where the job is running :param region: The Cloud Dataproc region in which to handle the request. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param polling_interval_seconds: polling period in seconds to check for the status """def__init__(self,cluster_name:str,**kwargs):super().__init__(**kwargs)self.cluster_name=cluster_name
[docs]defget_task_instance(self,session:Session)->TaskInstance:query=session.query(TaskInstance).filter(TaskInstance.dag_id==self.task_instance.dag_id,TaskInstance.task_id==self.task_instance.task_id,TaskInstance.run_id==self.task_instance.run_id,TaskInstance.map_index==self.task_instance.map_index,)task_instance=query.one_or_none()iftask_instanceisNone:raiseAirflowException("TaskInstance with dag_id: %s,task_id: %s, run_id: %s and map_index: %s is not found.",self.task_instance.dag_id,self.task_instance.task_id,self.task_instance.run_id,self.task_instance.map_index,)returntask_instance
[docs]defsafe_to_cancel(self)->bool:""" Whether it is safe to cancel the external job which is being executed by this trigger. This is to avoid the case that `asyncio.CancelledError` is called because the trigger itself is stopped. Because in those cases, we should NOT cancel the external job. """# Database query is needed to get the latest state of the task instance.task_instance=self.get_task_instance()# type: ignore[call-arg]returntask_instance.state!=TaskInstanceState.DEFERRED
[docs]asyncdefrun(self)->AsyncIterator[TriggerEvent]:try:whileTrue:cluster=awaitself.fetch_cluster()state=cluster.status.stateifstate==ClusterStatus.State.ERROR:awaitself.delete_when_error_occurred(cluster)yieldTriggerEvent({"cluster_name":self.cluster_name,"cluster_state":ClusterStatus.State.DELETING,"cluster":cluster,})returnelifstate==ClusterStatus.State.RUNNING:yieldTriggerEvent({"cluster_name":self.cluster_name,"cluster_state":state,"cluster":cluster,})returnself.log.info("Current state is %s",state)self.log.info("Sleeping for %s seconds.",self.polling_interval_seconds)awaitasyncio.sleep(self.polling_interval_seconds)exceptasyncio.CancelledError:try:ifself.delete_on_errorandself.safe_to_cancel():self.log.info("Deleting the cluster as it is safe to delete as the airflow TaskInstance is not in ""deferred state.")self.log.info("Deleting cluster %s.",self.cluster_name)# The synchronous hook is utilized to delete the cluster when a task is cancelled.# This is because the asynchronous hook deletion is not awaited when the trigger task# is cancelled. The call for deleting the cluster through the sync hook is not a blocking# call, which means it does not wait until the cluster is deleted.self.get_sync_hook().delete_cluster(region=self.region,cluster_name=self.cluster_name,project_id=self.project_id)self.log.info("Deleted cluster %s during cancellation.",self.cluster_name)exceptExceptionase:self.log.error("Error during cancellation handling: %s",e)raiseAirflowException("Error during cancellation handling: %s",e)
[docs]asyncdeffetch_cluster(self)->Cluster:"""Fetch the cluster status."""returnawaitself.get_async_hook().get_cluster(project_id=self.project_id,region=self.region,cluster_name=self.cluster_name)
[docs]asyncdefdelete_when_error_occurred(self,cluster:Cluster)->None:""" Delete the cluster on error. :param cluster: The cluster to delete. """ifself.delete_on_error:self.log.info("Deleting cluster %s.",self.cluster_name)awaitself.get_async_hook().delete_cluster(region=self.region,cluster_name=self.cluster_name,project_id=self.project_id)self.log.info("Cluster %s has been deleted.",self.cluster_name)else:self.log.info("Cluster %s is not deleted as delete_on_error is set to False.",self.cluster_name)
[docs]classDataprocBatchTrigger(DataprocBaseTrigger):""" DataprocCreateBatchTrigger run on the trigger worker to perform create Build operation. :param batch_id: The ID of the build. :param project_id: Google Cloud Project where the job is running :param region: The Cloud Dataproc region in which to handle the request. :param gcp_conn_id: Optional, the connection ID used to connect to Google Cloud Platform. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param polling_interval_seconds: polling period in seconds to check for the status """def__init__(self,batch_id:str,**kwargs):super().__init__(**kwargs)self.batch_id=batch_id
[docs]defserialize(self)->tuple[str,dict[str,Any]]:"""Serialize DataprocBatchTrigger arguments and classpath."""return("airflow.providers.google.cloud.triggers.dataproc.DataprocBatchTrigger",{"batch_id":self.batch_id,"project_id":self.project_id,"region":self.region,"gcp_conn_id":self.gcp_conn_id,"impersonation_chain":self.impersonation_chain,"polling_interval_seconds":self.polling_interval_seconds,},)
[docs]asyncdefrun(self):whileTrue:batch=awaitself.get_async_hook().get_batch(project_id=self.project_id,region=self.region,batch_id=self.batch_id)state=batch.stateifstatein(Batch.State.FAILED,Batch.State.SUCCEEDED,Batch.State.CANCELLED):breakself.log.info("Current state is %s",state)self.log.info("Sleeping for %s seconds.",self.polling_interval_seconds)awaitasyncio.sleep(self.polling_interval_seconds)yieldTriggerEvent({"batch_id":self.batch_id,"batch_state":state})
[docs]classDataprocDeleteClusterTrigger(DataprocBaseTrigger):""" DataprocDeleteClusterTrigger run on the trigger worker to perform delete cluster operation. :param cluster_name: The name of the cluster :param end_time: Time in second left to check the cluster status :param project_id: The ID of the Google Cloud project the cluster belongs to :param region: The Cloud Dataproc region in which to handle the request :param metadata: Additional metadata that is provided to the method :param gcp_conn_id: The connection ID to use when fetching connection info. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account. :param polling_interval_seconds: Time in seconds to sleep between checks of cluster status """def__init__(self,cluster_name:str,end_time:float,metadata:Sequence[tuple[str,str]]=(),**kwargs:Any,):super().__init__(**kwargs)self.cluster_name=cluster_nameself.end_time=end_timeself.metadata=metadata
[docs]defserialize(self)->tuple[str,dict[str,Any]]:"""Serialize DataprocDeleteClusterTrigger arguments and classpath."""return("airflow.providers.google.cloud.triggers.dataproc.DataprocDeleteClusterTrigger",{"cluster_name":self.cluster_name,"end_time":self.end_time,"project_id":self.project_id,"region":self.region,"metadata":self.metadata,"gcp_conn_id":self.gcp_conn_id,"impersonation_chain":self.impersonation_chain,"polling_interval_seconds":self.polling_interval_seconds,},)
[docs]asyncdefrun(self)->AsyncIterator[TriggerEvent]:"""Wait until cluster is deleted completely."""try:whileself.end_time>time.time():cluster=awaitself.get_async_hook().get_cluster(region=self.region,# type: ignore[arg-type]cluster_name=self.cluster_name,project_id=self.project_id,# type: ignore[arg-type]metadata=self.metadata,)self.log.info("Cluster status is %s. Sleeping for %s seconds.",cluster.status.state,self.polling_interval_seconds,)awaitasyncio.sleep(self.polling_interval_seconds)exceptNotFound:yieldTriggerEvent({"status":"success","message":""})exceptExceptionase:yieldTriggerEvent({"status":"error","message":str(e)})else:yieldTriggerEvent({"status":"error","message":"Timeout"})
[docs]classDataprocOperationTrigger(DataprocBaseTrigger):""" Trigger that periodically polls information on a long running operation from Dataproc API to verify status. Implementation leverages asynchronous transport. """def__init__(self,name:str,operation_type:str|None=None,**kwargs:Any):super().__init__(**kwargs)self.name=nameself.operation_type=operation_type
[docs]asyncdefrun(self)->AsyncIterator[TriggerEvent]:hook=self.get_async_hook()try:whileTrue:operation=awaithook.get_operation(region=self.region,operation_name=self.name)ifoperation.done:ifoperation.error.message:status="error"message=operation.error.messageelse:status="success"message="Operation is successfully ended."ifself.operation_type==DataprocOperationType.DIAGNOSE.value:gcs_regex=rb"gs:\/\/[a-z0-9][a-z0-9_-]{1,61}[a-z0-9_\-\/]*"gcs_uri_value=operation.response.valuematch=re.search(gcs_regex,gcs_uri_value)ifmatch:output_uri=match.group(0).decode("utf-8","ignore")else:output_uri=gcs_uri_valueyieldTriggerEvent({"status":status,"message":message,"output_uri":output_uri,})else:yieldTriggerEvent({"operation_name":operation.name,"operation_done":operation.done,"status":status,"message":message,})returnelse:self.log.info("Sleeping for %s seconds.",self.polling_interval_seconds)awaitasyncio.sleep(self.polling_interval_seconds)exceptExceptionase:self.log.exception("Exception occurred while checking operation status.")yieldTriggerEvent({"status":"failed","message":str(e),})