在气流EMR操作员步骤中使用Json输入变量

时间:2019-10-04 20:12:14

标签: airflow amazon-emr apache-airflow-xcom airflow-operator

我当前正在使用此处给出的模板:https://github.com/apache/airflow/blob/master/airflow/contrib/example_dags/example_emr_job_flow_manual_steps.py,用于创建DAG以使用spark提交来调用emr实例。设置spark_test_steps时,我需要包括从POST Json传入的变量,以填充Spark提交,如下所示:

SPARK_TEST_STEPS = [
    {
        'Name': 'calculate_pi',
        'ActionOnFailure': 'CONTINUE',
        'HadoopJarStep': {
            'Jar': 'command-runner.jar',
            'Args': [
                '/usr/lib/spark/bin/run-example',
                'SparkPi',
                kwargs['dag_run'].conf['var_1']
                kwargs['dag_run'].conf['var_2']
                '10'
            ]
        }
    }
]

我如何传递POST Json给定的变量,同时仍然遵循git链接中给定的格式,如下所示?

from datetime import timedelta
import airflow
from airflow import DAG
from airflow.contrib.operators.emr_create_job_flow_operator import EmrCreateJobFlowOperator
from airflow.contrib.operators.emr_add_steps_operator import EmrAddStepsOperator
from airflow.contrib.sensors.emr_step_sensor import EmrStepSensor
from airflow.contrib.operators.emr_terminate_job_flow_operator import EmrTerminateJobFlowOperator

DEFAULT_ARGS = {
    'owner': 'Airflow',
    'depends_on_past': False,
    'start_date': airflow.utils.dates.days_ago(2),
    'email': ['airflow@example.com'],
    'email_on_failure': False,
    'email_on_retry': False
}

dag = DAG(
    'emr_job_flow_manual_steps_dag',
    default_args=DEFAULT_ARGS,
    dagrun_timeout=timedelta(hours=2),
    schedule_interval='0 3 * * *'
)

var_1 = ''
var_2 = ''
SPARK_TEST_STEPS = []

def define_param(**kwargs):
    global var_1
    global var_2
    global SPARK_TEST_STEPS

    var_1 = str(kwargs['dag_run'].conf['var_1'])
    var_2 = str(kwargs['dag_run'].conf['var_2'])

    SPARK_TEST_STEPS = [
        {
            'Name': 'calculate_pi',
            'ActionOnFailure': 'CONTINUE',
            'HadoopJarStep': {
                'Jar': 'command-runner.jar',
                'Args': [
                    '/usr/lib/spark/bin/run-example',
                    'SparkPi',
                    kwargs['dag_run'].conf['var_1']
                    kwargs['dag_run'].conf['var_2']
                    '10'
                ]
            }
        }
    ]

    return SPARK_TEST_STEPS

DEFINE_PARAMETERS = PythonOperator(
    task_id='DEFINE_PARAMETERS',
    python_callable=define_param,
    provide_context=True,
    dag=dag)

cluster_creator = EmrCreateJobFlowOperator(
    task_id='create_job_flow',
    job_flow_overrides=JOB_FLOW_OVERRIDES,
    aws_conn_id='aws_default',
    emr_conn_id='emr_default',
    dag=dag
)

step_adder = EmrAddStepsOperator(
    task_id='add_steps',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow', key='return_value') }}",
    aws_conn_id='aws_default',
    steps='{{ ti.xcom_pull(task_ids="DEFINE_PARAMETERS") }}',
    dag=dag
)

step_checker = EmrStepSensor(
    task_id='watch_step',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow', key='return_value') }}",
    step_id="{{ task_instance.xcom_pull('add_steps', key='return_value')[0] }}",
    aws_conn_id='aws_default',
    dag=dag
)

cluster_remover = EmrTerminateJobFlowOperator(
    task_id='remove_cluster',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow', key='return_value') }}",
    aws_conn_id='aws_default',
    dag=dag
)

cluster_creator.set_downstream(step_adder)
step_adder.set_downstream(step_checker)
step_checker.set_downstream(cluster_remover)

我不能使用Variable.get和Variable.set,因为由于气流全局变量的不断变化,这将不允许同时对不同的变量类型进行多次dag调用。我曾尝试使用xcom调用SPARK_TEST_STEPS,但xcom的返回类型为字符串,并且EmrAddStepsOperator步骤需要一个列表。

1 个答案:

答案 0 :(得分:1)

我通过创建一个自定义运算符解决了类似的问题,该运算符在执行之前解析json。问题的原因是当您传递steps='{{ ti.xcom_pull(task_ids="DEFINE_PARAMETERS") }}',时。您实际上是在传递一个字符串,该字符串的值由模板引擎内插,但不会反序列化。

from airflow.contrib.hooks.emr_hook import EmrHook
from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults

from airflow.contrib.operators.emr_add_steps_operator import EmrAddStepsOperator
import json

class DynamicEmrStepsOperator(EmrAddStepsOperator):
    template_fields = ['job_flow_id', 'steps']
    template_ext = ()
    ui_color = '#f9c915'

    @apply_defaults
    def __init__(
            self,
            job_flow_id=None,
            steps="[]",
            *args, **kwargs):
        super().__init__(
                job_flow_id = job_flow_id,
                steps = steps,
                *args, **kwargs)

    def execute(self, context):
        self.steps = json.loads(self.steps)

        return super().execute(context)