Source code for airflow.providers.google.cloud.triggers.cloud_batch
# 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.from__future__importannotationsimportasynciofromtypingimportAny,AsyncIterator,Sequencefromgoogle.cloud.batch_v1importJob,JobStatusfromairflow.providers.google.cloud.hooks.cloud_batchimportCloudBatchAsyncHookfromairflow.triggers.baseimportBaseTrigger,TriggerEvent
[docs]classCloudBatchJobFinishedTrigger(BaseTrigger):"""Cloud Batch trigger to check if templated job has been finished. :param job_name: Required. Name of the job. :param project_id: Required. the Google Cloud project ID in which the job was started. :param location: Optional. the location where job is executed. If set to None then the value of DEFAULT_BATCH_LOCATION will be used :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :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 poll_sleep: Polling period in seconds to check for the status """def__init__(self,job_name:str,project_id:str|None,location:str=DEFAULT_BATCH_LOCATION,gcp_conn_id:str="google_cloud_default",impersonation_chain:str|Sequence[str]|None=None,polling_period_seconds:float=10,timeout:float|None=None,):super().__init__()self.project_id=project_idself.job_name=job_nameself.location=locationself.gcp_conn_id=gcp_conn_idself.polling_period_seconds=polling_period_secondsself.timeout=timeoutself.impersonation_chain=impersonation_chain
[docs]defserialize(self)->tuple[str,dict[str,Any]]:"""Serializes class arguments and classpath."""return("airflow.providers.google.cloud.triggers.cloud_batch.CloudBatchJobFinishedTrigger",{"project_id":self.project_id,"job_name":self.job_name,"location":self.location,"gcp_conn_id":self.gcp_conn_id,"polling_period_seconds":self.polling_period_seconds,"timeout":self.timeout,"impersonation_chain":self.impersonation_chain,},)
[docs]asyncdefrun(self)->AsyncIterator[TriggerEvent]:""" Main loop of the class in where it is fetching the job status and yields certain Event. If the job has status success then it yields TriggerEvent with success status, if job has status failed - with error status and if the job is being deleted - with deleted status. In any other case Trigger will wait for specified amount of time stored in self.polling_period_seconds variable. """timeout=self.timeouthook=self._get_async_hook()try:whiletimeoutisNoneortimeout>0:job:Job=awaithook.get_batch_job(job_name=self.job_name)status:JobStatus.State=job.status.stateifstatus==JobStatus.State.SUCCEEDED:yieldTriggerEvent({"job_name":self.job_name,"status":"success","message":"Job completed",})returnelifstatus==JobStatus.State.FAILED:yieldTriggerEvent({"job_name":self.job_name,"status":"error","message":f"Batch job with name {self.job_name} has failed its execution",})returnelifstatus==JobStatus.State.DELETION_IN_PROGRESS:yieldTriggerEvent({"job_name":self.job_name,"status":"deleted","message":f"Batch job with name {self.job_name} is being deleted",})returnelse:self.log.info("Current job status is: %s",status)self.log.info("Sleeping for %s seconds.",self.polling_period_seconds)iftimeoutisnotNone:timeout-=self.polling_period_secondsiftimeoutisNoneortimeout>0:awaitasyncio.sleep(self.polling_period_seconds)exceptExceptionase:self.log.exception("Exception occurred while checking for job completion.")yieldTriggerEvent({"status":"error","message":str(e)})returnself.log.exception(f"Job with name [{self.job_name}] timed out")yieldTriggerEvent({"job_name":self.job_name,"status":"timed out","message":f"Batch job with name {self.job_name} timed out",})