Source code for airflow.operators.python_operator

# -*- coding: utf-8 -*-## 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.importinspectimportosimportpickleimportsubprocessimportsysimporttypesfrombuiltinsimportstrfromtextwrapimportdedentimportdillimportsixfromairflow.exceptionsimportAirflowExceptionfromairflow.modelsimportBaseOperatorfromairflow.models.skipmixinimportSkipMixinfromairflow.utils.decoratorsimportapply_defaultsfromairflow.utils.fileimportTemporaryDirectoryfromairflow.utils.operator_helpersimportcontext_to_airflow_vars

[docs]classPythonOperator(BaseOperator):""" Executes a Python callable .. seealso:: For more information on how to use this operator, take a look at the guide: :doc:`howto/operator/python` :param python_callable: A reference to an object that is callable :type python_callable: python callable :param op_kwargs: a dictionary of keyword arguments that will get unpacked in your function :type op_kwargs: dict (templated) :param op_args: a list of positional arguments that will get unpacked when calling your callable :type op_args: list (templated) :param provide_context: if set to true, Airflow will pass a set of keyword arguments that can be used in your function. This set of kwargs correspond exactly to what you can use in your jinja templates. For this to work, you need to define `**kwargs` in your function header. :type provide_context: bool :param templates_dict: a dictionary where the values are templates that will get templated by the Airflow engine sometime between ``__init__`` and ``execute`` takes place and are made available in your callable's context after the template has been applied. (templated) :type templates_dict: dict[str] :param templates_exts: a list of file extensions to resolve while processing templated fields, for examples ``['.sql', '.hql']`` :type templates_exts: list[str] """template_fields=('templates_dict','op_args','op_kwargs')ui_color='#ffefeb'# since we won't mutate the arguments, we should just do the shallow copy# there are some cases we can't deepcopy the objects(e.g protobuf).shallow_copy_attrs=('python_callable','op_kwargs',)@apply_defaultsdef__init__(self,python_callable,op_args=None,op_kwargs=None,provide_context=False,templates_dict=None,templates_exts=None,*args,**kwargs):super(PythonOperator,self).__init__(*args,**kwargs)ifnotcallable(python_callable):raiseAirflowException('`python_callable` param must be callable')self.python_callable=python_callableself.op_args=op_argsor[]self.op_kwargs=op_kwargsor{}self.provide_context=provide_contextself.templates_dict=templates_dictiftemplates_exts:self.template_ext=templates_extsdefexecute(self,context):# Export context to make it available for callables to use.airflow_context_vars=context_to_airflow_vars(context,in_env_var_format=True)self.log.info("Exporting the following env vars:\n%s",'\n'.join(["{}={}".format(k,v)fork,vinairflow_context_vars.items()]))os.environ.update(airflow_context_vars)ifself.provide_context:context.update(self.op_kwargs)context['templates_dict']=self.templates_dictself.op_kwargs=contextreturn_value=self.execute_callable()self.log.info("Done. Returned value was: %s",return_value)returnreturn_valuedefexecute_callable(self):returnself.python_callable(*self.op_args,**self.op_kwargs)

[docs]classBranchPythonOperator(PythonOperator,SkipMixin):""" Allows a workflow to "branch" or follow a path following the execution of this task. It derives the PythonOperator and expects a Python function that returns a single task_id or list of task_ids to follow. The task_id(s) returned should point to a task directly downstream from {self}. All other "branches" or directly downstream tasks are marked with a state of ``skipped`` so that these paths can't move forward. The ``skipped`` states are propagated downstream to allow for the DAG state to fill up and the DAG run's state to be inferred. """defexecute(self,context):branch=super(BranchPythonOperator,self).execute(context)ifisinstance(branch,six.string_types):branch=[branch]self.log.info("Following branch %s",branch)self.log.info("Marking other directly downstream tasks as skipped")downstream_tasks=context['task'].downstream_listself.log.debug("Downstream task_ids %s",downstream_tasks)ifdownstream_tasks:# Also check downstream tasks of the branch task. In case the task to skip# is a downstream task of the branch task, we exclude it from skipping.branch_downstream_task_ids=set()forbinbranch:branch_downstream_task_ids.update(context["dag"].get_task(b).get_flat_relative_ids(upstream=False))skip_tasks=[tfortindownstream_tasksift.task_idnotinbranchandt.task_idnotinbranch_downstream_task_ids]self.skip(context['dag_run'],context['ti'].execution_date,skip_tasks)self.log.info("Done.")

[docs]classShortCircuitOperator(PythonOperator,SkipMixin):""" Allows a workflow to continue only if a condition is met. Otherwise, the workflow "short-circuits" and downstream tasks are skipped. The ShortCircuitOperator is derived from the PythonOperator. It evaluates a condition and short-circuits the workflow if the condition is False. Any downstream tasks are marked with a state of "skipped". If the condition is True, downstream tasks proceed as normal. The condition is determined by the result of `python_callable`. """defexecute(self,context):condition=super(ShortCircuitOperator,self).execute(context)self.log.info("Condition result is %s",condition)ifcondition:self.log.info('Proceeding with downstream tasks...')returnself.log.info('Skipping downstream tasks...')downstream_tasks=context['task'].get_flat_relatives(upstream=False)self.log.debug("Downstream task_ids %s",downstream_tasks)ifdownstream_tasks:self.skip(context['dag_run'],context['ti'].execution_date,downstream_tasks)self.log.info("Done.")

[docs]classPythonVirtualenvOperator(PythonOperator):""" Allows one to run a function in a virtualenv that is created and destroyed automatically (with certain caveats). The function must be defined using def, and not be part of a class. All imports must happen inside the function and no variables outside of the scope may be referenced. A global scope variable named virtualenv_string_args will be available (populated by string_args). In addition, one can pass stuff through op_args and op_kwargs, and one can use a return value. Note that if your virtualenv runs in a different Python major version than Airflow, you cannot use return values, op_args, or op_kwargs. You can use string_args though. :param python_callable: A python function with no references to outside variables, defined with def, which will be run in a virtualenv :type python_callable: function :param requirements: A list of requirements as specified in a pip install command :type requirements: list[str] :param python_version: The Python version to run the virtualenv with. Note that both 2 and 2.7 are acceptable forms. :type python_version: str :param use_dill: Whether to use dill to serialize the args and result (pickle is default). This allow more complex types but requires you to include dill in your requirements. :type use_dill: bool :param system_site_packages: Whether to include system_site_packages in your virtualenv. See virtualenv documentation for more information. :type system_site_packages: bool :param op_args: A list of positional arguments to pass to python_callable. :type op_kwargs: list :param op_kwargs: A dict of keyword arguments to pass to python_callable. :type op_kwargs: dict :param provide_context: if set to true, Airflow will pass a set of keyword arguments that can be used in your function. This set of kwargs correspond exactly to what you can use in your jinja templates. For this to work, you need to define `**kwargs` in your function header. :type provide_context: bool :param string_args: Strings that are present in the global var virtualenv_string_args, available to python_callable at runtime as a list[str]. Note that args are split by newline. :type string_args: list[str] :param templates_dict: a dictionary where the values are templates that will get templated by the Airflow engine sometime between ``__init__`` and ``execute`` takes place and are made available in your callable's context after the template has been applied :type templates_dict: dict of str :param templates_exts: a list of file extensions to resolve while processing templated fields, for examples ``['.sql', '.hql']`` :type templates_exts: list[str] """@apply_defaultsdef__init__(self,python_callable,requirements=None,python_version=None,use_dill=False,system_site_packages=True,op_args=None,op_kwargs=None,provide_context=False,string_args=None,templates_dict=None,templates_exts=None,*args,**kwargs):super(PythonVirtualenvOperator,self).__init__(python_callable=python_callable,op_args=op_args,op_kwargs=op_kwargs,templates_dict=templates_dict,templates_exts=templates_exts,provide_context=provide_context,*args,**kwargs)self.requirements=requirementsor[]self.string_args=string_argsor[]self.python_version=python_versionself.use_dill=use_dillself.system_site_packages=system_site_packages# check that dill is present if neededdill_in_requirements=map(lambdax:x.lower().startswith('dill'),self.requirements)if(notsystem_site_packages)anduse_dillandnotany(dill_in_requirements):raiseAirflowException('If using dill, dill must be in the environment '+'either via system_site_packages or requirements')# check that a function is passed, and that it is not a lambdaif(notisinstance(self.python_callable,types.FunctionType)or(self.python_callable.__name__==(lambdax:0).__name__)):raiseAirflowException('{} only supports functions for python_callable arg',self.__class__.__name__)# check that args are passed iff python major version matchesif(python_versionisnotNoneandstr(python_version)[0]!=str(sys.version_info[0])andself._pass_op_args()):raiseAirflowException("Passing op_args or op_kwargs is not supported across ""different Python major versions ""for PythonVirtualenvOperator. ""Please use string_args.")defexecute_callable(self):withTemporaryDirectory(prefix='venv')astmp_dir:ifself.templates_dict:self.op_kwargs['templates_dict']=self.templates_dict# generate filenamesinput_filename=os.path.join(tmp_dir,'script.in')output_filename=os.path.join(tmp_dir,'script.out')string_args_filename=os.path.join(tmp_dir,'string_args.txt')script_filename=os.path.join(tmp_dir,'script.py')# set up virtualenvself._execute_in_subprocess(self._generate_virtualenv_cmd(tmp_dir))cmd=self._generate_pip_install_cmd(tmp_dir)ifcmd:self._execute_in_subprocess(cmd)self._write_args(input_filename)self._write_script(script_filename)self._write_string_args(string_args_filename)# execute command in virtualenvself._execute_in_subprocess(self._generate_python_cmd(tmp_dir,script_filename,input_filename,output_filename,string_args_filename))returnself._read_result(output_filename)def_pass_op_args(self):# we should only pass op_args if any are given to usreturnlen(self.op_args)+len(self.op_kwargs)>0def_execute_in_subprocess(self,cmd):try:self.log.info("Executing cmd\n%s",cmd)output=subprocess.check_output(cmd,stderr=subprocess.STDOUT,close_fds=True)ifoutput:self.log.info("Got output\n%s",output)exceptsubprocess.CalledProcessErrorase:self.log.info("Got error output\n%s",e.output)raisedef_write_string_args(self,filename):# writes string_args to a file, which are read line by linewithopen(filename,'w')asf:f.write('\n'.join(map(str,self.string_args)))def_write_args(self,input_filename):# serialize args to fileifself._pass_op_args():withopen(input_filename,'wb')asf:arg_dict=({'args':self.op_args,'kwargs':self.op_kwargs})ifself.use_dill:dill.dump(arg_dict,f)else:pickle.dump(arg_dict,f)def_read_result(self,output_filename):ifos.stat(output_filename).st_size==0:returnNonewithopen(output_filename,'rb')asf:try:ifself.use_dill:returndill.load(f)else:returnpickle.load(f)exceptValueError:self.log.error("Error deserializing result. ""Note that result deserialization ""is not supported across major Python versions.")raisedef_write_script(self,script_filename):withopen(script_filename,'w')asf:python_code=self._generate_python_code()self.log.debug('Writing code to file\n{}'.format(python_code))f.write(python_code)def_generate_virtualenv_cmd(self,tmp_dir):cmd=['virtualenv',tmp_dir]ifself.system_site_packages:cmd.append('--system-site-packages')ifself.python_versionisnotNone:cmd.append('--python=python{}'.format(self.python_version))returncmddef_generate_pip_install_cmd(self,tmp_dir):iflen(self.requirements)==0:return[]else:# direct path alleviates need to activatecmd=['{}/bin/pip'.format(tmp_dir),'install']returncmd+self.requirements@staticmethoddef_generate_python_cmd(tmp_dir,script_filename,input_filename,output_filename,string_args_filename):# direct path alleviates need to activatereturn['{}/bin/python'.format(tmp_dir),script_filename,input_filename,output_filename,string_args_filename]def_generate_python_code(self):ifself.use_dill:pickling_library='dill'else:pickling_library='pickle'fn=self.python_callable# dont try to read pickle if we didnt pass anythingifself._pass_op_args():load_args_line='with open(sys.argv[1], "rb") as f: arg_dict = {}.load(f)'\
.format(pickling_library)else:load_args_line='arg_dict = {"args": [], "kwargs": {}}'# no indents in original code so we can accept# any type of indents in the original function# we deserialize args, call function, serialize result if necessaryreturndedent("""\ import {pickling_library} import sys{load_args_code} args = arg_dict["args"] kwargs = arg_dict["kwargs"] with open(sys.argv[3], 'r') as f: virtualenv_string_args = list(map(lambda x: x.strip(), list(f))){python_callable_lines} res = {python_callable_name}(*args, **kwargs) with open(sys.argv[2], 'wb') as f: res is not None and {pickling_library}.dump(res, f) """).format(load_args_code=load_args_line,python_callable_lines=dedent(inspect.getsource(fn)),python_callable_name=fn.__name__,pickling_library=pickling_library)