как установить air flow на windows

Опыт установки Apache Airflow на Windows 10

Преамбула: волею судьбы из мира академической науки (медицины) я попала в мир информационных технологий, где мне приходится использовать свои знания о методологии построения эксперимента и стратегиях анализа экспериментальных данных, однако, применять новый для меня стек технологий. В процессе освоения этих технологий я сталкиваюсь с рядом трудностей, которые пока, к счастью, удается преодолевать. Возможно, этот пост будет полезен тем, кто также только начинает работу с проектами Apache.

Итак, к сути. Вдохновившись статьей Юрия Емельянова о возможностях Apache Airflow в области автоматизации аналитических процедур, мне захотелось начать использовать предлагаемый набор библиотек в своей работе. Тем, кто еще совсем не знаком с Apache Airflow, может быть интересна небольшая обзорная статья на сайте Национальной библиотеки им. Н. Э. Баумана.

Поскольку обычные инструкции для запуска Airflow, судя по всему, не применяются в среде Windows, а использовать для решения данной задачи докер в моем случае было бы избыточно, я начала поиск других решений. К счастью для меня, я оказалась не первой на этом пути, поэтому мне удалось найти замечательную видео-инструкцию по установке Apache Airflow в Windows 10 без использования докера. Но, как это часто и бывает, при выполнении рекомендуемых шагов, возникают трудности, и, полагаю, не только у меня. Поэтому я хотела бы рассказать о своем опыте установки Apache Airflow, возможно кому-то это сэкономит немного времени.

Пройдемся по шагам инструкции (спойлер — 5-го шага все шло прекрасно):

1. Установка подсистемы Windows для Linux для последующей установки дистрибутивов Linux

Это меньшая из проблем, как говорится:

Панель управления → Программы → Программы и компоненты → Включение и отключение компонентов Windows → Подсистема Windows для Linux

2. Установка дистрибутива Linux по выбору

Я воспользовалась приложением Ubuntu.

3. Установка и апдейт pip

4. Установка Apache Airflow

5. Инициализация базы данных

Подробнее о werkzeug можно почитать здесь.

6. Запуск сервера Airflow

/.local/bin/ (то есть, добавив к существующему пути поиска исполняемых файлов, определяемому переменной PATH каталог /.local/bin/), но этот пост предназначен для тех, кто преимущественно работает с Windows и, возможно, не считает такое решение очевидным.

Если все прошло удачно на предыдущих этапах, то вы готовы покорять аналитические вершины.

Надеюсь, описанный выше опыт установки Apache Airflow на Windows 10 будет полезен начинающим пользователям и ускорит их вхождение во вселенную современных инструментов аналитики.

В следующий раз хотелось бы продолжить тему и рассказать об опыте использования Apache Airflow в сфере анализа поведения пользователей мобильных приложений.

Источник

DATAENGINER

Airflow — это потрясающий инструмент от Airbnb, который в настоящее время является своего рода стандартом развертывания ETL в области инженерии данных. Но в то же время вы также можете использовать Airflow для планирования конвейера машинного обучения и автоматизации всего конвейера машинного обучения (почти).

Установка Airflow

Шаг 1. Проверим что наша система использует последнюю версию пакетов для CentOS 7, проверять будет через менеджеров пакетов yum:

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Шаг 2. Для установки Airflow установим последнюю версию python3 и pip3-python, для этого выполним команду:

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Шаг 3. Создадим пользователя под которым будет работать airflow, пользователя назовем так же airflow:

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Шаг 4. Теперь при помощи менеджера пакетов python3 установим airflow и дополнительно необходимые пакеты crypto и пакет для работы с базой данных в моей случае postgres, так же для работы с базой данных вы можете установить mysql:

Будет установлено большое количество пакетов, необходимых для работы airflow:

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Будут проверены зависимости и при необходимости до установлены необходимые пакеты

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Также после данной команды будут проверены версии пакетов и до установлены пакеты для работы с СУБД PostgreSQL.

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Подготовка Демона Airflow

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Прежде чем мы сможем настроить наш systemd сервис для Airflow, нам нужно сделать некоторые приготовления. Первым шагом будет загрузка файлов определения службы из Airflow GitHub Репозитория.

Скачать служебные файлы демона

Шаг 5. Создадим временную папку для файлов загрузки.

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Шаг 6. Затем загрузим файлы во временную папку.

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

В репозитории GitHub есть следующее краткое объяснение:

Что ж, я полагаю, что для большинства тех, кто не знаком с Linux, приведенная выше документация может быть очень расплывчатой ​​и вводящей в заблуждение. Итак, я нарисовал эту диаграмму, чтобы показать, какой файл по какому пути следует поместить.

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Шаг 7. Скопируем файлы по пути, указанному на схеме:

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Шаг 9. Еще один каталог, который нам нужно создать, — это домашний каталог Airflow, который включает:

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Опять же, измените разрешение, чтобы разрешить всем пользователям в airflow группе не только читать, но и писать в каталог, потому что им нужны права чтобы изменить DAG.

Инициализация домашнего каталога Airflow

Шаг 10. Все готово. Теперь нам нужно инициализировать домашний каталог Airflow. Важно экспортировать домашний каталог в AIRFLOW_HOME переменную среды. В противном случае домашний каталог будет автоматически создан в домашней папке пользователя, как указано выше.

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Если же у вас возникла ошибка, как на приведенном скриншоте:

То необходимо переустановить cattrs пакет для python3, для этого выполните команду:

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

После чего повторите попытку инициализации базы данных

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Конфигурация Airflow Демона

Шаг 11. Теперь все служебные файлы, файлы конфигурации и необходимые каталоги готовы. Нам нужно настроить демон, чтобы убедиться, что все указывает на правильные пути, прежде чем демон сможет работать правильно.

Прежде всего, давайте дважды проверим путь к airflow двоичному файлу, потому что он должен быть указан в определении службы позже.

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Измените ExecStart значение следующим образом.

Затем нам нужно изменить системную конфигурацию Airflow. В противном случае службы не будут знать, где находится домашний каталог Airflow.

Две приведенные ниже конфигурации необходимо изменить следующим образом, исходя из того, что мы делали ранее:

На последнем этапе настройки служб нам необходимо включить эти службы, прежде чем мы сможем их запускать.

как установить air flow на windows. Смотреть фото как установить air flow на windows. Смотреть картинку как установить air flow на windows. Картинка про как установить air flow на windows. Фото как установить air flow на windows

Запустите настроенный демон Airflow

Шаг 12. Имея root разрешение (пользователь root или sudo), мы можем:

Резюме

В этой статье было рассказано, как установить Airflow в системе CentOS, что есть недостатки, если мы просто запускаем Airflow из командной строки, поэтому нам нужно решить эту проблему, запустив его как демон.

Сначала нам нужно загрузить файлы определения службы из репозитория Apache Airflow GitHub, а затем поместить их в правильные системные каталоги. Нам также необходимо создать несколько папок, потому что они потребуются демону для правильной работы.

Наконец, нам нужно настроить файлы определения службы, чтобы демон мог находить ресурсы в правильных местах. После этого мы можем запустить Apache Airflow как демон, чтобы он собирал соответствующие журналы выполнения служб, а также автоматически перезапускал службы, если что-то пойдет не так.

Источник

InstallationВ¶

This page describes installations options that you might use when considering how to install Airflow. Airflow consists of many components, often distributed among many physical or virtual machines, therefore installation of Airflow might be quite complex, depending on the options you choose.

You should also check-out the Prerequisites that must be fulfilled when installing Airflow as well as Supported versions to know what are the policies for supporting Airflow, Python and Kubernetes.

When you install Airflow, you need to setup the database which must also be kept updated when Airflow is upgraded.

As of June 2021 Airflow 1.10 is end-of-life and is not going to receive any fixes even critical security fixes. Follow the Upgrading from 1.10 to 2 to learn how to upgrade the end-of-life 1.10 to Airflow 2.

Using released sourcesВ¶

When this option works best

This option is best if you expect to build all your software from sources.

This is the best choice if you have a strong need to verify the integrity and provenance of the software

Intended users

Users who are familiar with installing and building software from sources and are conscious about integrity and provenance of the software they use down to the lowest level possible.

What are you expected to handle

You are expected to build and install airflow and its components on your own.

You should develop and handle the deployment for all components of Airflow.

You are responsible for setting up database, creating and managing database schema with airflow db commands, automated startup and recovery, maintenance, cleanup and upgrades of Airflow and the Airflow Providers.

What Apache Airflow Community provides for that method

You have instructions on how to build the software but due to various environments and tools you might want to use, you might expect that there will be problems which are specific to your deployment and environment you will have to diagnose and solve.

Where to ask for help

The #development slack channel for building the software.

The #troubleshooting slack is a channel for quick general troubleshooting questions. The GitHub discussions if you look for longer discussion and have more information to share.

If you can provide description of a reproducible problem with Airflow software, you can open issue at GitHub issues

Using PyPIВ¶

When this option works best

This installation method is useful when you are not familiar with Containers and Docker and want to install Apache Airflow on physical or virtual machines and you are used to installing and running software using custom deployment mechanism.

The only officially supported mechanism of installation is via pip using constraint mechanisms. The constraint files are managed by Apache Airflow release managers to make sure that you can repeatably install Airflow from PyPI with all Providers and required dependencies.

In case of PyPI installation you could also verify integrity and provenance of the packages of the packages downloaded from PyPI as described at the installation page, but software you download from PyPI is pre-built for you so that you can install it without building, and you do not build the software from sources.

Intended users

Users who are familiar with installing and configuring Python applications, managing Python environments, dependencies and running software with their custom deployment mechanisms.

What are you expected to handle

You should develop and handle the deployment for all components of Airflow.

You are responsible for setting up database, creating and managing database schema with airflow db commands, automated startup and recovery, maintenance, cleanup and upgrades of Airflow and Airflow Providers.

What Apache Airflow Community provides for that method

You have Installation from PyPI on how to install the software but due to various environments and tools you might want to use, you might expect that there will be problems which are specific to your deployment and environment you will have to diagnose and solve.

You have Running Airflow locally where you can see an example of Quick Start with running Airflow locally which you can use to start Airflow quickly for local testing and development. However this is just an inspiration. Do not expect this docker-compose is ready for production installation, you need to build your own production-ready deployment in this approach.

Where to ask for help

The #troubleshooting channel on Airflow Slack for quick general troubleshooting questions. The GitHub discussions if you look for longer discussion and have more information to share.

If you can provide description of a reproducible problem with Airflow software, you can open issue at GitHub issues

Using Production Docker ImagesВ¶

When this option works best

This installation method is useful when you are familiar with Container/Docker stack. It provides a capability of running Airflow components in isolation from other software running on the same physical or virtual machines with easy maintenance of dependencies.

The images are build by Apache Airflow release managers and they use officially released packages from PyPI and official constraint files- same that are used for installing Airflow from PyPI.

Intended users

Users who are familiar with Containers and Docker stack and understand how to build their own container images.

Users who understand how to install providers and dependencies from PyPI with constraints if they want to extend or customize the image.

Users who know how to create deployments using Docker by linking together multiple docker containers and maintaining such deployments.

What are you expected to handle

You are expected to be able to customize or extend Container/Docker images if you want to add extra dependencies. You are expected to put together a deployment built of several containers (for example using docker-compose) and to make sure that they are linked together.

You are responsible for setting up database, creating and managing database schema with airflow db commands, automated startup and recovery, maintenance, cleanup and upgrades of Airflow and the Airflow Providers.

You should choose the right deployment mechanism. There a number of available options of deployments of containers. You can use your own custom mechanism, custom Kubernetes deployments, custom Docker Compose, custom Helm charts etc., and you should choose it based on your experience and expectations.

What Apache Airflow Community provides for that method

You have instructions: Building the image on how to build and customize your image.

You have Running Airflow in Docker where you can see an example of Quick Start which you can use to start Airflow quickly for local testing and development. However this is just an inspiration. Do not expect to use this docker-compose.yml file for production installation, you need to get familiar with Docker Compose and its capabilities and build your own production-ready deployment with it if you choose Docker Compose for your deployment.

The Docker Image is managed by the same people who build Airflow, and they are committed to keep it updated whenever new features and capabilities of Airflow are released.

Where to ask for help

For quick questions with the Official Docker Image there is the #production-docker-image channel in Airflow Slack.

The #troubleshooting channel on Airflow Slack for quick general troubleshooting questions. The GitHub discussions if you look for longer discussion and have more information to share.

If you can provide description of a reproducible problem with Airflow software, you can open issue at GitHub issues

Using Official Airflow Helm ChartВ¶

When this option works best

This installation method is useful when you are not only familiar with Container/Docker stack but also when you use Kubernetes and want to install and maintain Airflow using the community-managed Kubernetes installation mechanism via Helm chart.

It provides not only a capability of running Airflow components in isolation from other software running on the same physical or virtual machines and managing dependencies, but also it provides capabilities of easier maintaining, configuring and upgrading Airflow in the way that is standardized and will be maintained by the community.

The Chart uses the Official Airflow Production Docker Images to run Airflow.

Intended users

Users who are familiar with Containers and Docker stack and understand how to build their own container images.

Users who understand how to install providers and dependencies from PyPI with constraints if they want to extend or customize the image.

Users who manage their infrastructure using Kubernetes and manage their applications on Kubernetes using Helm Charts.

What are you expected to handle

You are expected to be able to customize or extend Container/Docker images if you want to add extra dependencies. You are expected to put together a deployment built of several containers (for example using Docker Compose) and to make sure that they are linked together.

You are responsible for setting up database.

The Helm Chart manages your database schema, automates startup, recovery and restarts of the components of the application and linking them together, so you do not have to worry about that.

What Apache Airflow Community provides for that method

You have instructions: Building the image on how to build and customize your image.

The Helm Chart is managed by the same people who build Airflow, and they are committed to keep it updated whenever new features and capabilities of Airflow are released.

Where to ask for help

For quick questions with the Official Docker Image there is the #production-docker-image channel in Airflow Slack.

For quick questions with the official Helm Chart there is the #helm-chart-official channel in Slack.

The #troubleshooting channel on Airflow Slack for quick general troubleshooting questions. The GitHub discussions if you look for longer discussion and have more information to share.

If you can provide description of a reproducible problem with Airflow software, you can open issue at GitHub issues

Using Managed Airflow ServicesВ¶

Follow the Ecosystem page to find all Managed Services for Airflow.

When this option works best

When you prefer to have someone else manage Airflow installation for you, there are Managed Airflow Services that you can use.

Intended users

Users who prefer to get Airflow managed for them and want to pay for it.

What are you expected to handle

The Managed Services usually provide everything you need to run Airflow. Please refer to documentation of the Managed Services for details.

What Apache Airflow Community provides for that method

Airflow Community does not provide any specific documentation for managed services. Please refer to the documentation of the Managed Services for details.

Where to ask for help

Your first choice should be support that is provided by the Managed services. There are a few channels in the Apache Airflow Slack that are dedicated to different groups of users and if you have come to conclusion the question is more related to Airflow than the managed service, you can use those channels.

Using 3rd-party images, charts, deploymentsВ¶

Follow the Ecosystem page to find all 3rd-party deployment options.

When this option works best

Those installation methods are useful in case none of the official methods mentioned before work for you, or you have historically used those. It is recommended though that whenever you consider any change, you should consider switching to one of the methods that are officially supported by the Apache Airflow Community or Managed Services.

Intended users

Users who historically used other installation methods or find the official methods not sufficient for other reasons.

What are you expected to handle

Depends on what the 3rd-party provides. Look at the documentation of the 3rd-party.

What Apache Airflow Community provides for that method

Airflow Community does not provide any specific documentation for 3rd-party methods. Please refer to the documentation of the Managed Services for details.

Where to ask for help

Depends on what the 3rd-party provides. Look at the documentation of the 3rd-party deployment you use.

Источник

Опыт установки Apache Airflow на Windows 10

Категории

Свежие записи

Наши услуги

Преамбула: волею судьбы из мира академической науки (медицины) я попала в мир информационных технологий, где мне приходится использовать свои знания о методологии построения эксперимента и стратегиях анализа экспериментальных данных, однако, применять новый для меня стек технологий. В процессе освоения этих технологий я сталкиваюсь с рядом трудностей, которые пока, к счастью, удается преодолевать. Возможно, этот пост будет полезен тем, кто также только начинает работу с проектами Apache.

Итак, к сути. Вдохновившись статьей Юрия Емельянова о возможностях Apache Airflow в области автоматизации аналитических процедур, мне захотелось начать использовать предлагаемый набор библиотек в своей работе. Тем, кто еще совсем не знаком с Apache Airflow, может быть интересна небольшая обзорная статья на сайте Национальной библиотеки им. Н. Э. Баумана.

Поскольку обычные инструкции для запуска Airflow, судя по всему, не применяются в среде Windows, а использовать для решения данной задачи докер в моем случае было бы избыточно, я начала поиск других решений. К счастью для меня, я оказалась не первой на этом пути, поэтому мне удалось найти замечательную видео-инструкцию по установке Apache Airflow в Windows 10 без использования докера. Но, как это часто и бывает, при выполнении рекомендуемых шагов, возникают трудности, и, полагаю, не только у меня. Поэтому я хотела бы рассказать о своем опыте установки Apache Airflow, возможно кому-то это сэкономит немного времени.

Пройдемся по шагам инструкции (спойлер — 5-го шага все шло прекрасно):

1. Установка подсистемы Windows для Linux для последующей установки дистрибутивов Linux

Это меньшая из проблем, как говорится:

Панель управления → Программы → Программы и компоненты → Включение и отключение компонентов Windows → Подсистема Windows для Linux

2. Установка дистрибутива Linux по выбору

3. Установка и апдейт pip

4. Установка Apache Airflow

5. Инициализация базы данных

6. Запуск сервера Airflow

/.local/bin/ (то есть, добавив к существующему пути поиска исполняемых файлов, определяемому переменной PATH каталог /.local/bin/), но этот пост предназначен для тех, кто преимущественно работает с Windows и, возможно, не считает такое решение очевидным.

7. URL: localhost :8080/

Если все прошло удачно на предыдущих этапах, то вы готовы покорять аналитические вершины.

Надеюсь, описанный выше опыт установки Apache Airflow на Windows 10 будет полезен начинающим пользователям и ускорит их вхождение во вселенную современных инструментов аналитики.

В следующий раз хотелось бы продолжить тему и рассказать об опыте использования Apache Airflow в сфере анализа поведения пользователей мобильных приложений.

Добавить комментарий Отменить ответ

Для отправки комментария вам необходимо авторизоваться.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *