Checking if file exists in google bucket via apache airflow?

Viewed 2113

I have a DAG that takes the results of a script in a Google cloud bucket, loads it into a table in Google BigQuery, then deletes the file in the bucket.

I want the DAG to check every hour over the weekends. Right now, I'm using a GoogleCloudStoragetoBigQueryOperator. If the file is not there, the DAG fails. Is there a way I can set up the DAG to where it won't fail if the file isn't there? Maybe a try/catch?

1 Answers

You could use GCSObjectExistenceSensor from Google provider package in order to verify if the file is present before running downstream tasks.

gcs_object_exists = GCSObjectExistenceSensor(
    bucket=BUCKET_1,
    object=PATH_TO_UPLOAD_FILE,
    mode='poke',
    task_id="gcs_object_exists_task",
)

You can check the official example here. Keep in mind this sensor extends from BaseSensorOperator so you can define params such as poke_interval, timeout and mode to suit your needs.

  • soft_fail (bool) – Set to true to mark the task as SKIPPED on failure
  • poke_interval (float) – Time in seconds that the job should wait in between each tries
  • timeout (float) – Time, in seconds before the task times out and fails.
  • mode (str) – How the sensor operates. Options are: { poke | reschedule }, default is poke. When set to poke the sensor is taking up a worker slot for its whole execution time and sleeps between pokes. Use this mode if the expected runtime of the sensor is short or if a short poke interval is required. Note that the sensor will hold onto a worker slot and a pool slot for the duration of the sensor’s runtime in this mode. When set to reschedule the sensor task frees the worker slot when the criteria is not yet met and it’s rescheduled at a later time. Use this mode if the time before the criteria is met is expected to be quite long. The poke interval should be more than one minute to prevent too much load on the scheduler.
  • exponential_backoff (bool) – allow progressive longer waits between pokes by using exponential backoff algorithm

source

Related