Google Cloud Composer(Airflow) - dataflow job inside a DAG executes successfully, but the DAG fails
Asked Answered
D

2

8

My DAG looks like this

default_args = {
    'start_date': airflow.utils.dates.days_ago(0),
    'retries': 0,
    'dataflow_default_options': {
        'project': 'test',
        'tempLocation': 'gs://test/dataflow/pipelines/temp/',
        'stagingLocation': 'gs://test/dataflow/pipelines/staging/',
        'autoscalingAlgorithm': 'BASIC',
        'maxNumWorkers': '1',
        'region': 'asia-east1'
    }
}

dag = DAG(
    dag_id='gcs_avro_to_bq_dag',
    default_args=default_args,
    description='ETL for loading data from GCS(present in the avro format) to BQ',
    schedule_interval=None,
    dagrun_timeout=datetime.timedelta(minutes=30))

task = DataFlowJavaOperator(
    task_id='gcs_avro_to_bq_flow_job',
    jar='gs://test/dataflow/pipelines/jobs/test-1.0-SNAPSHOT.jar',
    poll_sleep=1,
    options={
        'input': '{{ ts }}',
    },
    dag=dag)

My DAG is executing a jar file. The jar file has the code for running a dataflow job which writes data to BQ from GCS. The jar by itself executes successfully.

When I try to execute the airflow job, I see the following errors

[2020-05-20 17:20:41,934] {base_task_runner.py:101} INFO - Job 274: Subtask gcs_avro_to_bq_flow_job [2020-05-20 17:20:41,840] {gcp_api_base_hook.py:97} INFO - Getting connection using `google.auth.default()` since no key file is defined for hook.
[2020-05-20 17:20:41,937] {base_task_runner.py:101} INFO - Job 274: Subtask gcs_avro_to_bq_flow_job [2020-05-20 17:20:41,853] {discovery.py:272} INFO - URL being requested: GET https://www.googleapis.com/discovery/v1/apis/dataflow/v1b3/rest
[2020-05-20 17:20:44,338] {base_task_runner.py:101} INFO - Job 274: Subtask gcs_avro_to_bq_flow_job [2020-05-20 17:20:44,338] {discovery.py:873} INFO - URL being requested: GET https://dataflow.googleapis.com/v1b3/projects/test/locations/asia-east1/jobs/asia-east1?alt=json
[2020-05-20 17:20:45,285] {__init__.py:1631} ERROR - <HttpError 404 when requesting https://dataflow.googleapis.com/v1b3/projects/test/locations/asia-east1/jobs/asia-east1?alt=json returned "(7e83a8221abb0a9b): Information about job asia-east1 could not be found in our system. Please double check the id is correct. If it is please contact customer support.">
Traceback (most recent call last)
  File "/usr/local/lib/airflow/airflow/models/__init__.py", line 1491, in _run_raw_tas
    result = task_copy.execute(context=context
  File "/usr/local/lib/airflow/airflow/contrib/operators/dataflow_operator.py", line 184, in execut
    self.jar, self.job_class
  File "/usr/local/lib/airflow/airflow/contrib/hooks/gcp_dataflow_hook.py", line 220, in start_java_dataflo
    self._start_dataflow(variables, name, command_prefix, label_formatter
  File "/usr/local/lib/airflow/airflow/contrib/hooks/gcp_api_base_hook.py", line 286, in wrappe
    return func(self, *args, **kwargs
  File "/usr/local/lib/airflow/airflow/contrib/hooks/gcp_dataflow_hook.py", line 200, in _start_dataflo
    self.poll_sleep, job_id).wait_for_done(
  File "/usr/local/lib/airflow/airflow/contrib/hooks/gcp_dataflow_hook.py", line 44, in __init_
    self._job = self._get_job(
  File "/usr/local/lib/airflow/airflow/contrib/hooks/gcp_dataflow_hook.py", line 63, in _get_jo
    jobId=self._job_id).execute(num_retries=5
  File "/opt/python3.6/lib/python3.6/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrappe
    return wrapped(*args, **kwargs
  File "/opt/python3.6/lib/python3.6/site-packages/googleapiclient/http.py", line 851, in execut
    raise HttpError(resp, content, uri=self.uri

I did some more digging and I can see the following API being called by airflow https://dataflow.googleapis.com/v1b3/projects/test/locations/asia-east1/jobs/asia-east1

As you can see the last param after jobs is asia-east, so I feel the airflow job is trying to use the region I have provided in the default_args to search for the status of the dataflow job. Not sure if that is what is going on, but just wanted to state that observation. Am I missing something in my flows DAG? Also my java job logic looks like this

public class GcsAvroToBQ {

    public interface Options extends PipelineOptions {
        @Description("Input")
        ValueProvider<String> getInput();

        void setInput(ValueProvider<String> value);
    }

    /**
     * Main entry point for executing the pipeline.
     *
     * @param args The command-line arguments to the pipeline.
     */
    public static void main(String[] args) {

        GcsAvroToBQ.Options options = PipelineOptionsFactory.fromArgs(args)
                .withValidation()
                .as(GcsAvroToBQ.Options.class);

        options.getJobName();

        run(options);
    }

    public static PipelineResult run(Options options) {
        // Create the pipeline
        Pipeline pipeline = Pipeline.create(options);

        // My Pipeline logic to read Avro and upload to BQ

        PCollection<TableRow> tableRowsForBQ; // Data to store in BQ
        tableRowsForBQ.apply(
                BigQueryIO.writeTableRows()
                        .to(bqDatasetName)
                        .withSchema(fieldSchemaListBuilder.schema())
                        .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
                        .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND));


        return pipeline.run();
    }
}
Douglass answered 20/5, 2020 at 17:49 Comment(5)
What region are you running your job in? Is it different than 'asia-east1'?Chagres
I have run the job both in asia-east1 and asia-south1, getting the same exception in both places.Douglass
What version of Airflow are you runningChagres
I am getting the same error msg on composer-1.10.4-airflow-1.10.6 and composer-1.10.4-airflow-1.10.3 in GCPDouglass
Could you try using a previous version of the SDK as suggested in the answer below, and let us know if that solves the issue?Chlodwig
D
6

This is a confirmed bug in the sdk version 2.20.0

https://github.com/apache/airflow/blob/master/airflow/providers/google/cloud/hooks/dataflow.py#L47

Please use 2.19.0 version and it should work correctly.

 <dependency>
  <groupId>org.apache.beam</groupId>
  <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
  <version>2.19.0</version>
  <scope>runtime</scope>
</dependency>
Destructible answered 26/5, 2020 at 17:11 Comment(0)
D
1

Since the fix hasn't been released yet although it is merged to the master I will add the following workaround for anyone that needs to use a more recent Beam SDK version than 2.19.0.

The idea is to implement the fix in a custom hook (identical to dataflow_hook.py but with the suggested change applied) and then implement a custom operator that uses this hook. Here is how I did it:

First, I created a file named my_dataflow_hook.py:

import re

from airflow.contrib.hooks.gcp_dataflow_hook import DataFlowHook, _Dataflow, _DataflowJob
from airflow.contrib.hooks.gcp_api_base_hook import GoogleCloudBaseHook


class _myDataflow(_Dataflow):
    @staticmethod
    def _extract_job(line):
        job_id_pattern = re.compile(
            br".*console.cloud.google.com/dataflow.*/jobs/.*/([a-z|0-9|A-Z|\-|\_]+).*")
        matched_job = job_id_pattern.search(line or '')
        if matched_job:
            return matched_job.group(1).decode()


class MyDataFlowHook(DataFlowHook):
    @GoogleCloudBaseHook._Decorators.provide_gcp_credential_file
    def _start_dataflow(self, variables, name, command_prefix, label_formatter):
        variables = self._set_variables(variables)
        cmd = command_prefix + self._build_cmd(variables, label_formatter)
        job_id = _myDataflow(cmd).wait_for_done()
        _DataflowJob(self.get_conn(), variables['project'], name,
                     variables['region'],
                     self.poll_sleep, job_id,
                     self.num_retries).wait_for_done()

Then, I created a file named my_dataflow_java_operator.py:

import copy

from airflow.contrib.operators.dataflow_operator import DataFlowJavaOperator, GoogleCloudBucketHelper
from hooks.my_dataflow_hook import MyDataFlowHook
from airflow.plugins_manager import AirflowPlugin


class MyDataFlowJavaOperator(DataFlowJavaOperator):
    def execute(self, context):
        bucket_helper = GoogleCloudBucketHelper(
            self.gcp_conn_id, self.delegate_to)
        self.jar = bucket_helper.google_cloud_to_local(self.jar)
        hook = MyDataFlowHook(gcp_conn_id=self.gcp_conn_id,
                            delegate_to=self.delegate_to,
                            poll_sleep=self.poll_sleep)

        dataflow_options = copy.copy(self.dataflow_default_options)
        dataflow_options.update(self.options)

        hook.start_java_dataflow(self.job_name, dataflow_options,
                                 self.jar, self.job_class)

class MyDataFlowPlugin(AirflowPlugin):
    """Expose Airflow operators."""

    name = 'dataflow_fix_plugin'
    operators = [MyDataFlowJavaOperator]

Finally, I uploaded these files into the bucket of the Composer environment following this structure:

├── dags
│   └── my_dag.py
└── plugins
    ├── hooks
    │   └── my_dataflow_hook.py
    └── my_dataflow_java_operator.py

Now, I can create tasks with MyDataFlowJavaOperator in my DAGs:

from airflow import DAG
from airflow.operators.dataflow_fix_plugin import MyDataFlowJavaOperator
...
with DAG("df-custom-test", default_args=default_args) as dag:
    test_task = MyDataFlowJavaOperator(dag=dag, task_id="df-java", py_file=PY_FILE, job_name=JOB_NAME)

Of course you can do the same with the DataFlowPythonOperator or the DataflowTemplateOperator if needed.

Derisible answered 23/7, 2020 at 16:6 Comment(1)
@routeburn Thanks for the edit. Indeed, it was a typo during copying and pasting the code in the answer.Derisible

© 2022 - 2024 — McMap. All rights reserved.