🚀 原文链接:https://airflow.apache.org/docs/apache-airflow/stable/tutorial.html

This tutorial walks you through some of the fundamental Airflow concepts, objects, and their usage while writing your first pipeline.

1、Example Pipeline definition

Here is an example of a basic pipeline definition. Do not worry if this looks complicated, a line by line explanation follows below.

airflow/example_dags/tutorial.py

  1. from datetime import timedelta
  2. from textwrap import dedent
  3. # The DAG object; we'll need this to instantiate a DAG
  4. from airflow import DAG
  5. # Operators; we need this to operate!
  6. from airflow.operators.bash import BashOperator
  7. from airflow.utils.dates import days_ago
  8. # These args will get passed on to each operator
  9. # You can override them on a per-task basis during operator initialization
  10. default_args = {
  11. 'owner': 'airflow',
  12. 'depends_on_past': False,
  13. 'email': ['airflow@example.com'],
  14. 'email_on_failure': False,
  15. 'email_on_retry': False,
  16. 'retries': 1,
  17. 'retry_delay': timedelta(minutes=5),
  18. # 'queue': 'bash_queue',
  19. # 'pool': 'backfill',
  20. # 'priority_weight': 10,
  21. # 'end_date': datetime(2016, 1, 1),
  22. # 'wait_for_downstream': False,
  23. # 'dag': dag,
  24. # 'sla': timedelta(hours=2),
  25. # 'execution_timeout': timedelta(seconds=300),
  26. # 'on_failure_callback': some_function,
  27. # 'on_success_callback': some_other_function,
  28. # 'on_retry_callback': another_function,
  29. # 'sla_miss_callback': yet_another_function,
  30. # 'trigger_rule': 'all_success'
  31. }
  32. with DAG(
  33. 'tutorial',
  34. default_args=default_args,
  35. description='A simple tutorial DAG',
  36. schedule_interval=timedelta(days=1),
  37. start_date=days_ago(2),
  38. tags=['example'],
  39. ) as dag:
  40. # t1, t2 and t3 are examples of tasks created by instantiating operators
  41. t1 = BashOperator(
  42. task_id='print_date',
  43. bash_command='date',
  44. )
  45. t2 = BashOperator(
  46. task_id='sleep',
  47. depends_on_past=False,
  48. bash_command='sleep 5',
  49. retries=3,
  50. )
  51. dag.doc_md = __doc__
  52. t1.doc_md = dedent(
  53. """\
  54. #### Task Documentation
  55. You can document your task using the attributes `doc_md` (markdown),
  56. `doc` (plain text), `doc_rst`, `doc_json`, `doc_yaml` which gets
  57. rendered in the UI's Task Instance Details page.
  58. ![img](http://montcs.bloomu.edu/~bobmon/Semesters/2012-01/491/import%20soul.png)
  59. """
  60. )
  61. templated_command = dedent(
  62. """
  63. {% for i in range(5) %}
  64. echo "{{ ds }}"
  65. echo "{{ macros.ds_add(ds, 7)}}"
  66. echo "{{ params.my_param }}"
  67. {% endfor %}
  68. """
  69. )
  70. t3 = BashOperator(
  71. task_id='templated',
  72. depends_on_past=False,
  73. bash_command=templated_command,
  74. params={'my_param': 'Parameter I passed in'},
  75. )
  76. t1 >> [t2, t3]

2、It’s a DAG definition file

One thing to wrap your head around (it may not be very intuitive(直观的) for everyone at first) is that this Airflow Python script is really just a configuration file specifying the DAG’s structure as code. The actual tasks defined here will run in a different context from the context of this script. Different tasks run on different workers at different points in time, which means that this script cannot be used to cross communicate between tasks. Note that for this purpose we have a more advanced feature called XComs.

People sometimes think of the DAG definition file as a place where they can do some actual data processing - that is not the case at all! The script’s purpose is to define a DAG object. It needs to evaluate quickly (seconds, not minutes) since the scheduler will execute it periodically to reflect the changes if any.

3、Importing Modules

An Airflow pipeline is just a Python script that happens to define an Airflow DAG object. Let’s start by importing the libraries we will need.

  1. from datetime import timedelta
  2. from textwrap import dedent
  3. # The DAG object; we'll need this to instantiate a DAG
  4. from airflow import DAG
  5. # Operators; we need this to operate!
  6. from airflow.operators.bash import BashOperator
  7. from airflow.utils.dates import days_ago

See Modules Management for details on how Python and Airflow manage modules.

4、Default Arguments

We’re about to create a DAG and some tasks, and we have the choice to explicitly pass a set of arguments to each task’s constructor (which would become redundant(多余的)), or (better!) we can define a dictionary of default parameters that we can use when creating tasks.

  1. # These args will get passed on to each operator
  2. # You can override them on a per-task basis during operator initialization
  3. default_args = {
  4. 'owner': 'airflow',
  5. 'depends_on_past': False,
  6. 'email': ['airflow@example.com'],
  7. 'email_on_failure': False,
  8. 'email_on_retry': False,
  9. 'retries': 1,
  10. 'retry_delay': timedelta(minutes=5),
  11. # 'queue': 'bash_queue',
  12. # 'pool': 'backfill',
  13. # 'priority_weight': 10,
  14. # 'end_date': datetime(2016, 1, 1),
  15. # 'wait_for_downstream': False,
  16. # 'dag': dag,
  17. # 'sla': timedelta(hours=2),
  18. # 'execution_timeout': timedelta(seconds=300),
  19. # 'on_failure_callback': some_function,
  20. # 'on_success_callback': some_other_function,
  21. # 'on_retry_callback': another_function,
  22. # 'sla_miss_callback': yet_another_function,
  23. # 'trigger_rule': 'all_success'
  24. }

For more information about the BaseOperator’s parameters and what they do, refer to the airflow.models.BaseOperator documentation.

Also, note that you could easily define different sets of arguments that would serve different purposes. An example of that would be to have different settings between a production and development environment.

5、Instantiate a DAG

We’ll need a DAG object to nest(嵌套信息) our tasks into. Here we pass a string that defines the dag_id, which serves as a unique identifier for your DAG. We also pass the default argument dictionary that we just defined and define a schedule_interval of 1 day for the DAG.

  1. t1 = BashOperator(
  2. task_id='print_date',
  3. bash_command='date',
  4. )
  5. t2 = BashOperator(
  6. task_id='sleep',
  7. depends_on_past=False,
  8. bash_command='sleep 5',
  9. retries=3,
  10. )

6、Tasks

Tasks are generated when instantiating operator objects. An object instantiated from an operator is called a task. The first argument task_id acts as a unique identifier for the task.

  1. t1 = BashOperator(
  2. task_id='print_date',
  3. bash_command='date',
  4. )
  5. t2 = BashOperator(
  6. task_id='sleep',
  7. depends_on_past=False,
  8. bash_command='sleep 5',
  9. retries=3,
  10. )

Notice how we pass a mix of operator specific arguments (bash_command) and an argument common to all operators (retries) inherited from BaseOperator to the operator’s constructor. This is simpler than passing every argument for every constructor call. Also, notice that in the second task we override the retries parameter with 3.

The precedence rules(优先规则) for a task are as follows:

  1. Explicitly passed arguments
  2. Values that exist in the default_args dictionary
  3. The operator’s default value, if one exists

A task must include or inherit the arguments task_id and owner, otherwise Airflow will raise an exception.

7、Templating with Jinja

Airflow leverages(借助) the power of Jinja Templating and provides the pipeline author with a set of built-in parameters and macros. Airflow also provides hooks for the pipeline author to define their own parameters, macros and templates.

This tutorial barely(仅仅) scratches the surface(触及表面) of what you can do with templating in Airflow, but the goal of this section is to let you know this feature exists, get you familiar with double curly brackets, and point to the most common template variable: {{ ds }} (today’s “date stamp”).

  1. templated_command = dedent(
  2. """
  3. {% for i in range(5) %}
  4. echo "{{ ds }}"
  5. echo "{{ macros.ds_add(ds, 7)}}"
  6. echo "{{ params.my_param }}"
  7. {% endfor %}
  8. """
  9. )
  10. t3 = BashOperator(
  11. task_id='templated',
  12. depends_on_past=False,
  13. bash_command=templated_command,
  14. params={'my_param': 'Parameter I passed in'},
  15. )

Notice that the templated_command contains code logic in {% %} blocks, references parameters like {{ ds }}, calls a function as in {{ macros.ds_add(ds, 7)}}, and references a user-defined parameter in {{ params.my_param }}.

The params hook in BaseOperator allows you to pass a dictionary of parameters and/or objects to your templates. Please take the time to understand how the parameter my_param makes it through to the template.

Files can also be passed to the bash_command argument, like bash_command='templated_command.sh', where the file location is relative to the directory containing the pipeline file (tutorial.py in this case). This may be desirable for many reasons, like separating your script’s logic and pipeline code, allowing for proper code highlighting in files composed in different languages, and general flexibility in structuring pipelines. It is also possible to define your template_searchpath as pointing to any folder locations in the DAG constructor call.

Using that same DAG constructor call, it is possible to define user_defined_macros which allow you to specify your own variables. For example, passing dict(foo='bar') to this argument allows you to use {{ foo }} in your templates. Moreover(而且), specifying user_defined_filters allows you to register your own filters. For example, passing dict(hello=lambda name: 'Hello %s' % name) to this argument allows you to use {{ 'world' | hello }} in your templates. For more information regarding custom filters have a look at the Jinja Documentation.

For more information on the variables and macros that can be referenced in templates, make sure to read through the Macros reference.

8、Adding DAG and Tasks documentation

We can add documentation for DAG or each single task. DAG documentation only support markdown so far and task documentation support plain text, markdown, reStructuredText, json, yaml.

  1. dag.doc_md = __doc__
  2. t1.doc_md = dedent(
  3. """\
  4. #### Task Documentation
  5. You can document your task using the attributes `doc_md` (markdown),
  6. `doc` (plain text), `doc_rst`, `doc_json`, `doc_yaml` which gets
  7. rendered in the UI's Task Instance Details page.
  8. ![img](http://montcs.bloomu.edu/~bobmon/Semesters/2012-01/491/import%20soul.png)
  9. """
  10. )

9、Setting up Dependencies

We have tasks t1, t2 and t3 that do not depend on each other. Here’s a few ways you can define dependencies between them:

  1. t1.set_downstream(t2)
  2. # This means that t2 will depend on t1
  3. # running successfully to run.
  4. # It is equivalent to:
  5. t2.set_upstream(t1)
  6. # The bit shift operator can also be
  7. # used to chain operations:
  8. t1 >> t2
  9. # And the upstream dependency with the
  10. # bit shift operator:
  11. t2 << t1
  12. # Chaining multiple dependencies becomes
  13. # concise with the bit shift operator:
  14. t1 >> t2 >> t3
  15. # A list of tasks can also be set as
  16. # dependencies. These operations
  17. # all have the same effect:
  18. t1.set_downstream([t2, t3])
  19. t1 >> [t2, t3]
  20. [t2, t3] << t1

Note that when executing your script, Airflow will raise exceptions when it finds cycles in your DAG or when a dependency is referenced more than once.

10、Recap

Alright, so we have a pretty basic DAG. At this point your code should look something like this:

  1. from datetime import timedelta
  2. from textwrap import dedent
  3. # The DAG object; we'll need this to instantiate a DAG
  4. from airflow import DAG
  5. # Operators; we need this to operate!
  6. from airflow.operators.bash import BashOperator
  7. from airflow.utils.dates import days_ago
  8. # These args will get passed on to each operator
  9. # You can override them on a per-task basis during operator initialization
  10. default_args = {
  11. 'owner': 'airflow',
  12. 'depends_on_past': False,
  13. 'email': ['airflow@example.com'],
  14. 'email_on_failure': False,
  15. 'email_on_retry': False,
  16. 'retries': 1,
  17. 'retry_delay': timedelta(minutes=5),
  18. # 'queue': 'bash_queue',
  19. # 'pool': 'backfill',
  20. # 'priority_weight': 10,
  21. # 'end_date': datetime(2016, 1, 1),
  22. # 'wait_for_downstream': False,
  23. # 'dag': dag,
  24. # 'sla': timedelta(hours=2),
  25. # 'execution_timeout': timedelta(seconds=300),
  26. # 'on_failure_callback': some_function,
  27. # 'on_success_callback': some_other_function,
  28. # 'on_retry_callback': another_function,
  29. # 'sla_miss_callback': yet_another_function,
  30. # 'trigger_rule': 'all_success'
  31. }
  32. with DAG(
  33. 'tutorial',
  34. default_args=default_args,
  35. description='A simple tutorial DAG',
  36. schedule_interval=timedelta(days=1),
  37. start_date=days_ago(2),
  38. tags=['example'],
  39. ) as dag:
  40. # t1, t2 and t3 are examples of tasks created by instantiating operators
  41. t1 = BashOperator(
  42. task_id='print_date',
  43. bash_command='date',
  44. )
  45. t2 = BashOperator(
  46. task_id='sleep',
  47. depends_on_past=False,
  48. bash_command='sleep 5',
  49. retries=3,
  50. )
  51. dag.doc_md = __doc__
  52. t1.doc_md = dedent(
  53. """\
  54. #### Task Documentation
  55. You can document your task using the attributes `doc_md` (markdown),
  56. `doc` (plain text), `doc_rst`, `doc_json`, `doc_yaml` which gets
  57. rendered in the UI's Task Instance Details page.
  58. ![img](http://montcs.bloomu.edu/~bobmon/Semesters/2012-01/491/import%20soul.png)
  59. """
  60. )
  61. templated_command = dedent(
  62. """
  63. {% for i in range(5) %}
  64. echo "{{ ds }}"
  65. echo "{{ macros.ds_add(ds, 7)}}"
  66. echo "{{ params.my_param }}"
  67. {% endfor %}
  68. """
  69. )
  70. t3 = BashOperator(
  71. task_id='templated',
  72. depends_on_past=False,
  73. bash_command=templated_command,
  74. params={'my_param': 'Parameter I passed in'},
  75. )
  76. t1 >> [t2, t3]

11、Testing

11.1 Running the Script

Time to run some tests. First, let’s make sure the pipeline is parsed successfully.

Let’s assume we are saving the code from the previous step in tutorial.py in the DAGs folder referenced in your airflow.cfg. The default location for your DAGs is ~/airflow/dags.

  1. $ python ~/airflow/dags/tutorial.py

If the script does not raise an exception it means that you have not done anything horribly wrong, and that your Airflow environment is somewhat sound.

11.2 Command Line Metadata Validation

Let’s run a few commands to validate this script further.

  1. # initialize the database tables
  2. $ airflow db init
  3. # print the list of active DAGs
  4. $ airflow dags list
  5. # prints the list of tasks in the "tutorial" DAG
  6. $ airflow tasks list tutorial
  7. # prints the hierarchy of tasks in the "tutorial" DAG
  8. $ airflow tasks list tutorial --tree

11.3 Testing

Let’s test by running the actual task instances for a specific date. The date specified in this context is called execution_date. This is the logical date, which simulates the scheduler running your task or dag at a specific date and time, even though it physically will run now ( or as soon as its dependencies are met).

  1. # command layout: command subcommand dag_id task_id date
  2. # testing print_date
  3. $ airflow tasks test tutorial print_date 2015-06-01
  4. # testing sleep
  5. $ airflow tasks test tutorial sleep 2015-06-01

Now remember what we did with templating earlier? See how this template gets rendered and executed by running this command:

  1. # testing templated
  2. $ airflow tasks test tutorial templated 2015-06-01

This should result in displaying a verbose log of events and ultimately(最终) running your bash command and printing the result.

Note that the airflow tasks test command runs task instances locally, outputs their log to stdout (on screen), does not bother with dependencies, and does not communicate state (running, success, failed, …) to the database. It simply allows testing a single task instance.

The same applies to airflow dags test [dag_id] [execution_date], but on a DAG level. It performs a single DAG run of the given DAG id. While it does take task dependencies into account, no state is registered in the database. It is convenient for locally testing a full run of your DAG, given that e.g. if one of your tasks expects data at some location, it is available.

11.4 Backfill

Everything looks like it’s running fine so let’s run a backfill. backfill will respect your dependencies, emit(发出) logs into files and talk to the database to record status. If you do have a webserver up, you will be able to track the progress. airflow webserver will start a web server if you are interested in tracking the progress visually as your backfill progresses.

Note that if you use depends_on_past=True, individual task instances will depend on the success of their previous task instance (that is, previous according to execution_date). Task instances with execution_date==start_date will disregard(不理会) this dependency because there would be no past task instances created for them.

You may also want to consider wait_for_downstream=True when using depends_on_past=True. While depends_on_past=True causes a task instance to depend on the success of its previous taskinstance, wait_for_downstream=True will cause a task instance to also wait for all task instances _immediately downstream of the previous task instance to succeed.

The date range in this context is a start_date and optionally an end_date, which are used to populate the run schedule with task instances from this dag.

  1. # optional, start a web server in debug mode in the background
  2. # airflow webserver --debug &
  3. # start your backfill on a date range
  4. $ airflow dags backfill tutorial \
  5. --start-date 2015-06-01 \
  6. --end-date 2015-06-07

12、What’s Next?

That’s it, you have written, tested and backfilled your very first Airflow pipeline. Merging your code into a code repository that has a master scheduler running against it should get it to get triggered and run every day.

Here’s a few things you might want to do next: :::info See also:

:::