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__importannotationsimportasyncioimporttimefromtypingimportAny,AsyncIterator,Sequencefromgoogle.api_core.exceptionsimportNotFoundfromgoogle.cloud.dataproc_v1importBatch,ClusterStatus,JobStatusfromairflow.exceptionsimportAirflowExceptionfromairflow.providers.google.cloud.hooks.dataprocimportDataprocAsyncHookfromairflow.triggers.baseimportBaseTrigger,TriggerEvent
[docs]classDataprocBaseTrigger(BaseTrigger):"""Base class for Dataproc triggers."""def__init__(self,region:str,project_id:str|None=None,gcp_conn_id:str="google_cloud_default",impersonation_chain:str|Sequence[str]|None=None,polling_interval_seconds:int=30,):super().__init__()self.region=regionself.project_id=project_idself.gcp_conn_id=gcp_conn_idself.impersonation_chain=impersonation_chainself.polling_interval_seconds=polling_interval_seconds
[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]asyncdefrun(self):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):breakelifstate==JobStatus.State.ERROR:raiseAirflowException(f"Dataproc job execution failed {self.job_id}")awaitasyncio.sleep(self.polling_interval_seconds)yieldTriggerEvent({"job_id":self.job_id,"job_state":state})
[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]asyncdefrun(self)->AsyncIterator[TriggerEvent]:whileTrue:cluster=awaitself.get_async_hook().get_cluster(project_id=self.project_id,region=self.region,cluster_name=self.cluster_name)state=cluster.status.stateself.log.info("Dataproc cluster: %s is in state: %s",self.cluster_name,state)ifstatein(ClusterStatus.State.ERROR,ClusterStatus.State.RUNNING,):breakself.log.info("Sleeping for %s seconds.",self.polling_interval_seconds)awaitasyncio.sleep(self.polling_interval_seconds)yieldTriggerEvent({"cluster_name":self.cluster_name,"cluster_state":state,"cluster":cluster})
[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]]:"""Serializes 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]]:"""Serializes 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]classDataprocWorkflowTrigger(DataprocBaseTrigger):""" Trigger that periodically polls information from Dataproc API to verify status. Implementation leverages asynchronous transport. """def__init__(self,name:str,**kwargs:Any):super().__init__(**kwargs)self.name=name
[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."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),})