Что такое pipeline в gitlab

GitLab CI для непрерывной интеграции и доставки в production. Часть 1: наш пайплайн

Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

Итак, GitLab CI: что можно ещё рассказать о нём? На хабре уже есть статьи про установку, про настройку раннеров, про командное использование, про GitLab Flow. Пожалуй, не хватает описаний того, как используется GitLab CI в реальном проекте, где задействовано несколько команд. А в современном мире разработки ПО это действительно так: ведь есть (как минимум) разработчики, тестировщики, DevOps- и релиз-инженеры. С подобным разделением на команды мы работаем уже несколько лет. В этой статье я расскажу о том, как мы, используя и улучшая возможности GitLab CI, реализовали и применяем в production для коллектива из нескольких команд процессы непрерывной интеграции (CI) и отчасти доставки приложений (CD).

Наш пайплайн

Если вы сталкивались с CI-системами ранее, то понятие пайплайна вам знакомо — это последовательность выполнения стадий (здесь и далее в статье для термина stage использую перевод «стадия»), каждая из которых включает несколько задач (здесь и далее в статье job — «задача»). От момента внесения изменений в код до выката в production приложение по очереди оказывается в руках разных команд — подобному тому, как это происходит на конвейере. Отсюда и возник термин pipeline («конвейер» — один из вариантов дословного перевода). В нашем случае это выглядит так:

Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

Краткие пояснения по используемым стадиям:

Как это используется?

Начну с рассказа о пайплайне с точки зрения его использования — то, что можно назвать user story. Тут выяснится, что на самом деле пайплайна у нас даже два: укороченный для веток и полноценный для тегов. И вот как выглядят эти последовательности:

Пайплайн и стадии в деталях

Задачи на стадии build собирают приложение. Для этого мы используем свою разработку — Open Source-утилиту dapp (о её основных возможностях читайте и смотрите в этой статье + видео), которая хорошо ускоряет инкрементальную сборку. Поэтому сборка запускается автоматически для веток с префиксами feature_ (код приложения), infra_ (код инфраструктуры) и тегов, а не только для нескольких традиционно «главных» веток (master/develop/production/release).

Обновлено 06 сентября 2019 г.: в настоящее время проект dapp переименован в werf, его код переписан на Go, а документация значительно улучшена.

Следующая стадия — staging — это набор сред для разработчиков, DevOps-инженеров и тестировщиков. Здесь объявлено несколько задач, разворачивающих приложения из веток с префиксами feature_ и infra_ в урезанных средах для быстрого тестирования новой функциональности или инфраструктурных изменений (код сборки приложения хранится в репозитории приложения).

Стадии pre-production и production доступны только для тегов. Обычно тег вешается после того, как релиз-инженеры принимают несколько merge-запросов из протестированных веток. В целом можно сказать, что мы используем GitLab Flow с тем лишь отличием, что нет автоматического развёртывания на production и потому нет отдельных веток, а используются теги.

Стадия approve — это две задачи: approve и not approve. Первая включает возможность развёртывания на production, вторая — выключает. Эти задачи существуют для того, чтобы в случае проблем на production было видно, что развёртывание происходило не просто так, а с согласия релиз-инженера. Однако суть не в лишении кого-то премии, а в том, что непосредственно развёртывание на production проводит зачастую не сам релиз-инженер, а команда DevOps. Релиз-инженер, запуская задачу approve, разрешает тем самым «нажать на кнопку» deploy to production команде DevOps. Можно сказать, что эта стадия выносит на поверхность то, что могло бы остаться в почтовой переписке или в устной форме.

Такая схема взаимодействия хорошо себя показала в работе, однако пришлось потрудиться, чтобы реализовать её. Как оказалось, GitLab CI не поддерживает из коробки некоторые нужные вещи…

Всё довольно просто и скорее всего понятно. Для каждой задачи используются следующие директивы:

Он демонстрирует возможность формата YAML определять общие блоки и подключать их в нужное место на нужном уровне. Подробнее см. в документации.

Таким образом, задачи на стадиях build, testing, staging, pre-production, которые должны быть доступны для веток infra_, feature_ и тегов, принимают следующий вид:

А задачи на стадиях approve и production, которые доступны только для тегов, имеют такой вид:

Что дальше?

Полная реализация задуманного стала возможной только благодаря нескольким патчам к GitLab и использованию артефактов задач. Подробнее об этом читайте в следующей части статьи: «GitLab CI для непрерывной интеграции и доставки в production. Часть 2: преодолевая трудности».

Источник

Как запустить несколько пайплайнов с помощью GitLab CI/CD

Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

Запуск и визуализация пайплайнов при настройке GitLab CI/CD для нескольких проектов.

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

Хотя CI проверяет, что новый код не сломается при интеграции с другим кодом в том же репо, прохождение всех тестов на этом репо — это только первый шаг. После запуска CI в коде важно развернуть и запустить тесты в реальной среде. Переход от CI к непрерывной доставке и деплою (CD) является следующим шагом к “взрослому” DevOps. Развертывание и последующее повторное тестирование позволяют тестировать код одного проекта вместе с другими компонентами и сервисами, которые, возможно, управляются другими проектами.

Зачем мне нужно убедиться, что мой код работает с другими компонентами?

Хорошим примером может служить архитектура микросервисов. Обычно микросервисы управляются в разных проектах, где каждый микросервис имеет свой собственный репозиторий с пайплайном. Кроме того, очень часто каждая команда разработчиков несёт ответственность за отдельные микросервисы и конфигурации пайплайнов. Как программист, вы возможно захотите убедиться, что изменения в вашем коде не нарушают функциональность зависимых от него микросервисов. Поэтому вы можете запускать тесты на них дополнительно к тестам для вашего проекта.

Пайплайн кросс-проекта

При запуске пайплайна проекта, вам также нужно будет запустить кросс-проектные пайплайны, которые в конечном итоге развернут и протестируют последнюю версию всех зависимых микросервисов. Для достижения этой цели вам нужен простой, гибкий и удобный способ запуска других пайплайнов в рамках CI вашего проекта. GitLab CI/CD предлагает легкий путь запуска кросс-проектного пайплайна путем добавления специального задания в файл конфигурации CI.

GitLab CI/CD конфигурационный файл

Добавление job для запуска кросс-проектного пайплайна

Начиная с GitLab 11.8, GitLab предоставляет новый синтаксис конфигурации CI/CD для запуска кросс-проектных пайплайнов, его можно найти в правилах конфигурации пайплайна. Следующий код иллюстрирует настройку bridge job для запуска нисходящего пайплайна:

В приведенном выше примере, как только deploy job (задача развертывания) на этапе деплоя выполнится успешно, запустится задание для Android bridge. Его первоначальный статус будет в ожидании. GitLab создаст нисходящий пайплайн в проекте mobile/android, и, как только он будет создан, Android job выполнится успешно. В этом случае mobile/android является полным путем к этому проекту.

Пользователь, создавший вышестоящий пайплайн, должен иметь права доступа к нижестоящему проекту (в данном случае mobile / android). Если нижестоящий проект не может быть найден или у пользователя нет прав доступа для создания там пайплайна, Android job получит статус failed.

Обзор графиков от восходящего до нижестоящего пайплайна

GitLab CI/CD позволяет визуализировать конфигурацию пайплайна. На приведенном ниже рисунке этапы сборки, тестирования и деплоя являются частями восходящего (upstream) проекта. Как только deploy job выполнено успешно, четыре кросс-проекта будут запущены параллельно, и вы сможете перейти к ним, щелкнув на одну из нисходящих (downstream) job.

Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

На приведенном ниже рисунке виден нисходящий пайплайн «Сервис — Финансы». Теперь можно прокрутить влево к восходящему пайплайну, прокрутить вправо назад к нисходящему или выбрать другой нисходящий пайплайн.

Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

Определение ветки нижестоящего пайплайна

Можно указать имя ветки, которое будет использовать нисходящий пайплайн:

Используйте ключевое слово проекта, чтобы указать полный путь к нисходящему проекту. Используйте ключевое слово branch, чтобы определить имя ветки. GitLab будет использовать коммит, который в данный момент находится в HEAD ветки при создании нисходящего пайплайна.

Передача переменных в нисходящий пайплайн

Когда-нибудь вам возможно захочется передать переменные в нисходящий пайплайн. Вы можете сделать это с помощью ключевых слов для переменных, как и при определении обычной job.

Переменная ENVIRONMENT будет передаваться каждой job, определенной в нисходящем пайплайне. Она будет доступна в качестве переменной среды каждый раз, когда GitLab Runner выбирает job.

Итого о кросс-проектном пайплайне

Пайплайны могут быть сложными структурами с множеством последовательных и параллельных задач, и, как мы только что узнали, иногда они могут запускать нисходящие пайплайны. Чтобы упростить понимание потока пайплайна, включая нисходящие пайплайны, в GitLab есть графики пайплайнов для просмотра пайплайнов и их статусов.

Источник

CI/CD pipelines

Pipelines are the top-level component of continuous integration, delivery, and deployment.

Jobs are executed by runners. Multiple jobs in the same stage are executed in parallel, if there are enough concurrent runners.

If all jobs in a stage succeed, the pipeline moves on to the next stage.

If any job in a stage fails, the next stage is not (usually) executed and the pipeline ends early.

In general, pipelines are executed automatically and require no intervention once created. However, there are also times when you can manually interact with a pipeline.

Types of pipelines

Configure a pipeline

For a list of configuration options in the CI pipeline file, see the GitLab CI/CD Pipeline Configuration Reference.

Ref specs for runners

When a runner picks a pipeline job, GitLab provides that job’s metadata. This includes the Git refspecs, which indicate which ref (branch, tag, and so on) and commit (SHA1) are checked out from your project repository.

This table lists the refspecs injected for each pipeline type:

Pipeline type

Refspecs

pipeline for branches

+ :refs/pipelines/ and +refs/heads/ :refs/remotes/origin/

pipeline for tags

+ :refs/pipelines/ and +refs/tags/ :refs/tags/

pipeline for merge requests

+ :refs/pipelines/

The refs refs/heads/ and refs/tags/ exist in your project repository. GitLab generates the special ref refs/pipelines/ during a running pipeline job. This ref can be created even after the associated branch or tag has been deleted. It’s therefore useful in some features such as automatically stopping an environment, and merge trains that might run pipelines after branch deletion.

View pipelines

You can find the current and historical pipeline runs under your project’s CI/CD > Pipelines page. You can also access pipelines for a merge request by navigating to its Pipelines tab.

Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

Click a pipeline to open the Pipeline Details page and show the jobs that were run for that pipeline. From here you can cancel a running pipeline, retry jobs on a failed pipeline, or delete a pipeline.

Starting in GitLab 14.2, you can change the pipeline column to display the pipeline ID or the pipeline IID.

If you use VS Code to edit your GitLab CI/CD configuration, the GitLab Workflow VS Code extension helps you validate your configuration and view your pipeline status.

Run a pipeline manually

Pipelines can be manually executed, with predefined or manually-specified variables.

You might do this if the results of a pipeline (for example, a code build) are required outside the normal operation of the pipeline.

The pipeline now executes the jobs as configured.

Prefill variables in manual pipelines

You can use the value and description keywords to define pipeline-level (global) variables that are prefilled when running a pipeline manually.

The description is displayed next to the variable. It can be used to explain what the variable is used for, what the acceptable values are, and so on:

You cannot set job-level variables to be pre-filled when you run a pipeline manually.

Run a pipeline by using a URL query string

The format of the pipelines/new URL is:

Add manual interaction to your pipeline

Manual jobs, allow you to require manual interaction before moving forward in the pipeline.

You can do this straight from the pipeline graph. Just click the play button to execute that particular job.

For example, your pipeline can start automatically, but require a manual action to deploy to production. In the example below, the production stage has a job with a manual action:

Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

Start multiple manual actions in a stage

Multiple manual actions in a single stage can be started at the same time using the “Play all manual” button. After you click this button, each individual manual action is triggered and refreshed to an updated status.

Skip a pipeline

Alternatively, if you are using Git 2.10 or later, use the ci.skip Git push option. The ci.skip push option does not skip merge request pipelines.

Delete a pipeline

Users with the Owner role in a project can delete a pipeline by clicking on the pipeline in the CI/CD > Pipelines to get to the Pipeline Details page, then using the Delete button.

Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

Pipeline security on protected branches

A strict security model is enforced when pipelines are executed on protected branches.

Variables marked as protected are accessible only to jobs that run on protected branches, preventing untrusted users getting unintended access to sensitive information like deployment credentials and tokens.

Runners marked as protected can run jobs only on protected branches, preventing untrusted code from executing on the protected runner and preserving deployment keys and other credentials from being unintentionally accessed. In order to ensure that jobs intended to be executed on protected runners do not use regular runners, they must be tagged accordingly.

How pipeline duration is calculated

Total running time for a given pipeline excludes retries and pending (queued) time.

Visually, it can be viewed as:

The union of A, B, and C is (1, 4) and (6, 7). Therefore, the total running time is:

Visualize pipelines

Pipelines can be complex structures with many sequential and parallel jobs.

To make it easier to understand the flow of a pipeline, GitLab has pipeline graphs for viewing pipelines and their statuses.

Pipeline graphs can be displayed as a large graph or a miniature representation, depending on the page you access the graph from.

GitLab capitalizes the stages’ names in the pipeline graphs.

View full pipeline graph

The pipeline details page displays the full pipeline graph of all the jobs in the pipeline.

You can group the jobs by:

    Stage, which arranges jobs in the same stage together in the same column:

    Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

    Job dependencies, which arranges jobs based on their needs dependencies.

    Multi-project pipeline graphs help you visualize the entire pipeline, including all cross-project inter-dependencies.

    View job dependencies in the pipeline graph

    You can arrange jobs in the pipeline graph based on their needs dependencies.

    Jobs in the leftmost column run first, and jobs that depend on them are grouped in the next columns.

    For example, test-job1 depends only on jobs in the first column, so it displays in the second column from the left. deploy-job1 depends on jobs in both the first and second column and displays in the third column:

    Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

    To add lines that show the needs relationships between jobs, select the Show dependencies toggle. These lines are similar to the needs visualization:

    Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

    To see the full needs dependency tree for a job, hover over it:

    Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

    Pipeline mini graphs

    Pipeline mini graphs allow you to see all related jobs for a single commit and the net result of each stage of your pipeline. This allows you to quickly see what failed and fix it.

    Pipeline mini graphs only display jobs by stage.

    Stages in pipeline mini graphs are collapsible. Hover your mouse over them and click to expand their jobs.

    Mini graph

    Mini graph expanded

    Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

    Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

    Pipeline success and duration charts

    Pipeline analytics are available on the CI/CD Analytics page.

    Pipeline badges

    Pipeline status and test coverage report badges are available and configurable for each project. For information on adding pipeline badges to projects, see Pipeline badges.

    Pipelines API

    Источник

    Almat.su (Almat.pro)

    Блог Алмата Жандаулетова

    Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

    Что такое pipeline в gitlab. Смотреть фото Что такое pipeline в gitlab. Смотреть картинку Что такое pipeline в gitlab. Картинка про Что такое pipeline в gitlab. Фото Что такое pipeline в gitlab

    Gitlab CI/CD на примере PHP проекта

    В этой статье мы воспользуемся замечательным инструментом Gitlab CI/CD для автоматизации непрерывной интеграции. На примере PHP проекта, который включает в себя этапы: composer install, то есть установка всех зависимостей и библиотек; этап тестирования, запуск юнит тестов; и наконец деплой на сервер, в качестве которого будет выступать облачный PAAS Heroku; познакомимся с понятиями конвейера или pipeline, конфигурацией через gitlab-ci.yml, артефактами, разделением всего этого на stages и запуском jobs. Поехали…

    Что такое Gitlab?

    Gitlab это такой Github на стероидах, по крайнем мере был им. Сейчас после покупки Github-a Microsoft, после колоссальных вложений, на Github-е начали появляться новые фишки: Github Actions, проверка кода и, после многолетнего ожидания, впервые появились бесплатные приватные репозитории 😮. Молодец Microsoft. А ведь старички знают, все эти штуки изначально были в Gitlab. СI/CD и пайплайн одним из первых появился на Gitlab. Помню, когда пайплайн только только начал внедряться в Bitbucket, на Gitlab он уже существовал давно. Еще Bitbucket для бесплатного пользования pipeline предлагал 500 минут в месяц, в то время как Gitlab, уже на тот момент, предлагал 2000 минут для бесплатного аккаунта!

    Конечно не забываем о такой киллер фиче, как установка Gitlab на собственном сервере. Интересно, когда такое Github внедрить…

    Что такое CI/CD Pipeline?
    PHP «MVP»

    Что из себя должен представлять минимальный PHP проект. Естественно он должен собираться через composer, иметь отделенный от корня проекта entrypoint(public/index.php), запускаться на PHP > 7, и конечно же иметь автотесты. Много автотестов, которые запускаются автоматически 🙂

    Также он должен быстро доставляться до клиента, то есть на прод.

    Gitlab CI/CD дает нам такие прекрасные возможности и нужно ими воспользоваться. У нас будут три шага, от начала написания кода, до доставки всего этого на сервер.

    Build — наш проект будет автоматически собираться из репозитория, устанавливаться все зависимости и пакеты, чтобы он был готов к запуску.

    Tests — проверка кода, запуск тестирования, поиск потенциальных багов, проверка на прочность.

    Deploy — деплой на сервер, внесение изменении в видимый продукт.

    Как начать?

    В конечном итоге, наш файл будет выглядеть так:

    Источник

    Pipelines for the GitLab project

    We’re striving to dogfood GitLab CI/CD features and best-practices as much as possible.

    Minimal test jobs before a merge request is approved

    To reduce the pipeline cost and shorten the job duration, before a merge request is approved, the pipeline will run a minimal set of RSpec & Jest tests that are related to the merge request changes.

    After a merge request has been approved, the pipeline would contain the full RSpec & Jest tests. This will ensure that all tests have been run before a merge request is merged.

    Overview of the GitLab project test dependency

    To understand how the minimal test jobs are executed, we need to understand the dependency between GitLab code (frontend and backend) and the respective tests (Jest and RSpec). This dependency can be visualized in the following diagram:

    RSpec minimal jobs

    Determining related RSpec test files in a merge request

    The test mappings contain a map of each source files to a list of test files which is dependent of the source file.

    In the detect-tests job, we use this mapping to identify the minimal tests needed for the current merge request.

    Exceptional cases

    Jest minimal jobs

    Determining related Jest test files in a merge request

    Exceptional cases

    Fail-fast job in merge request pipelines

    To provide faster feedback when a merge request breaks existing tests, we are experimenting with a fail-fast mechanism.

    An rspec fail-fast job is added in parallel to all other rspec jobs in a merge request pipeline. This job runs the tests that are directly related to the changes in the merge request.

    The rspec fail-fast is a no-op if there are more than 10 test files related to the merge request. This prevents rspec fail-fast duration from exceeding the average rspec job duration and defeating its purpose.

    Test jobs

    We have dedicated jobs for each testing level and each job runs depending on the changes made in your merge request. If you want to force all the RSpec jobs to run regardless of your changes, you can add the pipeline:run-all-rspec label to the merge request.

    Test suite parallelization

    After that, the next pipeline uses the up-to-date knapsack/report-master.json file.

    Flaky tests

    «pipeline:run-flaky-tests» label is set on the MR

    Monitoring

    The GitLab test suite is monitored for the main branch, and any branch that includes rspec-profile in their name.

    Logging

    Review app jobs

    Consult the Review Apps dedicated page for more information.

    If you want to force a Review App to be deployed regardless of your changes, you can add the pipeline:run-review-app label to the merge request.

    As-if-FOSS jobs

    The * as-if-foss jobs are run in addition to the regular EE-context jobs. They have the FOSS_ONLY=’1′ variable set and get the ee/ folder removed before the tests start running.

    The intent is to ensure that a change doesn’t introduce a failure after the gitlab-org/gitlab project is synced to the gitlab-org/gitlab-foss project.

    As-if-JH jobs

    The * as-if-jh jobs are run in addition to the regular EE-context jobs. The jh/ folder is added before the tests start running.

    The intent is to ensure that a change doesn’t introduce a failure after the gitlab-org/gitlab project is synced to the gitlab-jh/gitlab project.

    Corresponding JH branch

    undercover RSpec test

    The rspec:undercoverage job runs undercover to detect, and fail if any changes introduced in the merge request has zero coverage.

    The rsepc:undercoverage job obtains coverage data from the rspec:coverage job.

    In the event of an emergency, or false positive from this job, add the pipeline:skip-undercoverage label to the merge request to allow this job to fail.

    PostgreSQL versions testing

    Our test suite runs against PG12 as GitLab.com runs on PG12 and Omnibus defaults to PG12 for new installs and upgrades.

    We do run our test suite against PG11 and PG13 on nightly scheduled pipelines.

    We also run our test suite against PG11 upon specific database library changes in MRs and main pipelines (with the rspec db-library-code pg11 job).

    Current versions testing

    Where?

    PostgreSQL version

    MRs

    12, 11 for DB library changes

    main (non-scheduled pipelines)

    12, 11 for DB library changes

    2-hourly scheduled pipelines

    12, 11 for DB library changes

    nightly scheduled pipelines

    12, 11, 13

    Long-term plan

    We follow the PostgreSQL versions shipped with Omnibus GitLab:

    PostgreSQL version

    14.1 (July 2021)

    14.2 (August 2021)

    14.3 (September 2021)

    14.4 (October 2021)

    14.5 (November 2021)

    14.6 (December 2021)

    PG12

    MRs/ 2-hour / nightly

    MRs/ 2-hour / nightly

    MRs/ 2-hour / nightly

    MRs/ 2-hour / nightly

    MRs/ 2-hour / nightly

    MRs/ 2-hour / nightly

    PG11

    nightly

    nightly

    nightly

    nightly

    nightly

    nightly

    PG13

    nightly

    nightly

    nightly

    nightly

    nightly

    nightly

    Pipelines types for merge requests

    A “pipeline type” is an abstract term that mostly describes the “critical path” (i.e. the chain of jobs for which the sum of individual duration equals the pipeline’s duration). We use these “pipeline types” in metrics dashboards in order to detect what types and jobs need to be optimized first.

    An MR that touches multiple areas would be associated with the longest type applicable. For instance, an MR that touches backend and frontend would fall into the “Frontend” pipeline type since this type takes longer to finish than the “Backend” pipeline type.

    We use the rules: and needs: keywords extensively to determine the jobs that need to be run in a pipeline. Note that an MR that includes multiple types of changes would have a pipelines that include jobs from multiple types (for example, a combination of docs-only and code-only pipelines).

    Following are graphs of the critical paths for each pipeline type. Jobs that aren’t part of the critical path are ommitted.

    Documentation pipeline

    Backend pipeline

    Frontend pipeline

    End-to-end pipeline

    CI configuration internals

    Workflow rules

    Pipelines for the GitLab project are created using the workflow:rules keyword feature of the GitLab CI/CD.

    No pipeline is created in any other cases (for example, when pushing a branch with no MR for it).

    Default image

    It includes Ruby, Go, Git, Git LFS, Chrome, Node, Yarn, PostgreSQL, and Graphics Magick.

    The images used in our pipelines are configured in the gitlab-org/gitlab-build-images project, which is push-mirrored to gitlab/gitlab-build-images for redundancy.

    The current version of the build images can be found in the “Used by GitLab section”.

    Default variables

    Stages

    Dependency Proxy

    Common job definitions

    We’re using the rules keyword extensively.

    The rules definitions are composed of if: conditions and changes: patterns, which are also defined in rules.gitlab-ci.yml and included in rules definitions via YAML anchors

    if: conditions

    ”pipeline:run-as-if-foss”

    if-merge-request-title-update-caches

    Matches if the pipeline is for a merge request and the MR has label

    ”pipeline:update-cache”.

    if-merge-request-title-run-all-rspec

    Matches if the pipeline is for a merge request and the MR has label

    changes: patterns

    Performance

    Interruptible pipelines

    If you want a running pipeline to finish even if you push new commits to a merge request, be sure to start the dont-interrupt-me job before pushing.

    Caching strategy

    Artifacts strategy

    We limit the artifacts that are saved and retrieved by jobs to the minimum in order to reduce the upload/download time and costs, as well as the artifacts storage.

    Источник

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

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