Como criar um plug-in personalizado para PythonVirtualEnvOperator do Apache Airflow
O exemplo a seguir explica como corrigir o PythonVirtualenvOperator do Apache Airflow com um plug-in personalizado no Amazon Managed Workflows para o Apache Airflow.
Tópicos
Versão
É possível usar o exemplo de código nesta página com o Apache Airflow v2 no Python 3.10
Pré-requisitos
Para usar o código de amostra nesta página, você precisará do seguinte:
Permissões
Nenhuma permissão adicional é necessária para usar o exemplo de código nesta página.
Requisitos
Para usar o código de amostra nesta página, adicione as seguintes dependências ao seu requirements.txt. Consulte Como instalar dependências do Python para saber mais.
virtualenv
Código de exemplo de plugin personalizado
O Apache Airflow executará o conteúdo dos arquivos Python na pasta de plugins na inicialização. Esse plug-in corrigirá o PythonVirtualenvOperator integrado durante o processo de inicialização para torná-lo compatível com o Amazon MWAA. As seguintes etapas exibem o exemplo de código para o plugin personalizado.
-
Em seu prompt de comando, navegue até o diretório
pluginsda etapa anterior. Por exemplo:cd plugins -
Copie o conteúdo da amostra de código a seguir e salve localmente como
virtual_python_plugin.py.""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from airflow.plugins_manager import AirflowPlugin import airflow.utils.python_virtualenv from typing import List def _generate_virtualenv_cmd(tmp_dir: str, python_bin: str, system_site_packages: bool) -> List[str]: cmd = ['python3','/usr/local/airflow/.local/lib/python3.7/site-packages/virtualenv', tmp_dir] if system_site_packages: cmd.append('--system-site-packages') if python_bin is not None: cmd.append(f'--python={python_bin}') return cmd airflow.utils.python_virtualenv._generate_virtualenv_cmd=_generate_virtualenv_cmd class VirtualPythonPlugin(AirflowPlugin): name = 'virtual_python_plugin'
Plugins.zip
As etapas a seguir explicam como criar plugins.zip.
-
Em seu prompt de comando, navegue até o diretório que contém
virtual_python_plugin.pyda etapa anterior. Por exemplo:cd plugins -
Compacte o conteúdo em sua pasta
plugins.zip plugins.zip virtual_python_plugin.py
Exemplo de código
As etapas a seguir descrevem como criar o código do DAG para o plugin personalizado.
-
No prompt de comando, navegue até o diretório em que o código do DAG está armazenado. Por exemplo:
cd dags -
Copie o conteúdo da amostra de código a seguir e salve localmente como
virtualenv_test.py.""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from airflow import DAG from airflow.operators.python import PythonVirtualenvOperator from airflow.utils.dates import days_ago import os os.environ["PATH"] = os.getenv("PATH") + ":/usr/local/airflow/.local/bin" def virtualenv_fn(): import boto3 print("boto3 version ",boto3.__version__) with DAG(dag_id="virtualenv_test", schedule_interval=None, catchup=False, start_date=days_ago(1)) as dag: virtualenv_task = PythonVirtualenvOperator( task_id="virtualenv_task", python_callable=virtualenv_fn, requirements=["boto3>=1.17.43"], system_site_packages=False, dag=dag, )
Opções de configuração do Airflow
Se você estiver usando o Apache Airflow v2, adicione core.lazy_load_plugins : False como uma opção de configuração do Apache Airflow. Para saber mais, consulte Usar opções de configuração para carregar plug-ins em 2.
Próximas etapas
-
Saiba como fazer o upload do
requirements.txtarquivo neste exemplo para seu bucket do Amazon S3 em Como instalar dependências do Python. -
Saiba como fazer o upload do código DAG neste exemplo para a pasta
dagsem seu bucket do Amazon S3 em Como adicionar ou atualizar DAGs. -
Saiba mais sobre como fazer o upload do
plugins.ziparquivo neste exemplo para seu bucket do Amazon S3 em Como instalar plug-ins personalizados.