Gitlab runner очистить кэш
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
GitLab Runner Commands
GitLab Runner contains a set of commands with which you register, manage and run your builds.
You can check a recent list of commands by executing:
Append --help after a command to see its specific help page:
Table of Contents generated with DocToc
Using environment variables
Most of the commands support environment variables as a method to pass the configuration to the command.
You can see the name of the environment variable when invoking --help for a specific command. For example, you can see below the help message for the run command:
The output would be similar to:
Running in debug mode
Debug mode is especially useful when looking for the cause of some undefined behavior or error.
To run a command in debug mode, prepend the command with --debug :
Commands that access the configuration of GitLab Runner behave differently when executed as super-user ( root ). The file location depends on the user executing the command.
Be aware of the notice that is written when executing the commands that are used for running builds, registering services or managing registered runners:
You should use user-mode if you are really sure that this is a mode that you want to work with. Otherwise, prefix your command with sudo :
In the case of Windows you may need to run the Command Prompt in Administrative Mode.
GitLab Runner configuration uses the TOML format.
The file to be edited can be found in:
- /etc/gitlab-runner/config.toml on *nix systems when gitlab-runner is executed as super-user ( root )
- ~/.gitlab-runner/config.toml on *nix systems when gitlab-runner is executed as non-root
- ./config.toml on other systems
Most of the commands accept an argument to specify a custom configuration file, allowing you to have a multiple different configurations on a single machine. To specify a custom configuration file use the -c or --config flag, or use the CONFIG_FILE environment variable.
It is possible to use system signals to interact with GitLab Runner. The following commands support the following signals:
Command | Signal | Action |
---|---|---|
register | SIGINT | Cancel runner registration and delete if it was already registered |
run , exec , run-single | SIGINT, SIGTERM | Abort all running builds and exit as soon as possible. Use twice to exit now (forceful shutdown). |
run , exec , run-single | SIGQUIT | Stop accepting a new builds. Exit as soon as currently running builds do finish (graceful shutdown). |
run | SIGHUP | Force to reload configuration file |
This is what you see if you run gitlab-runner without any arguments:
Below we will explain what each command does in detail.
The following commands allow you to register a new runner, or list and verify them if they are still registered.
The above commands support the following arguments:
Parameter | Default | Description |
---|---|---|
--config | See the configuration file section | Specify a custom configuration file to be used |
This command registers your GitLab Runner in GitLab. The registered runner is added to the configuration file. You can use multiple configurations in a single GitLab Runner. Executing gitlab-runner register adds a new configuration entry, it doesn't remove the previous ones.
There are two options to register a Runner, interactive and non-interactive.
This command is usually used in interactive mode (default). You will be asked multiple questions during a Runner's registration.
This question can be pre-filled by adding arguments when invoking the registration command:
Or by configuring the environment variable before the register command:
To check all possible arguments and environments execute:
It's possible to use registration in non-interactive / unattended mode.
You can specify the arguments when invoking the registration command:
Or by configuring the environment variable before the register command:
This command lists all runners saved in the configuration file.
This command checks if the registered runners can connect to GitLab, but it doesn't verify if the runners are being used by the GitLab Runner service. An example output is:
To delete the old and removed from GitLab runners, execute the following command.
Warning: This operation cannot be undone, it will update the configuration file, so make sure to have a backup of config.toml before executing it.
This command allows to unregister one of the registered runners. It expects either a full URL and the runner's token, or the runner's name. First get the runner's details by executing gitlab-runner list :
Then use this information to unregister it, using one of the following commands.
Warning: This operation cannot be undone, it will update the configuration file, so make sure to have a backup of config.toml before executing it.
By URL and token:
Note: If there is more than one runner with the given name, only the first one will be removed
The following commands allow you to manage the runner as a system or user service. Use them to install, uninstall, start and stop the runner service.
All service related commands accept these arguments:
Parameter | Default | Description |
---|---|---|
--service-name | gitlab-runner | Specify custom service name |
--config | See the configuration file | Specify a custom configuration file to use |
This command installs GitLab Runner as a service. It accepts different sets of arguments depending on which system it's run on.
When run on Windows or as super-user, it accepts the --user flag which allows you to drop privileges of builds run with the shell executor.
Parameter | Default | Description |
---|---|---|
--service-name | gitlab-runner | Specify a custom name for the Runner |
--working-directory | the current directory | Specify the root directory where all data will be stored when builds will be run with the shell executor |
--user | root | Specify the user which will be used to execute builds |
--password | none | Specify the password for the user that will be used to execute the builds |
This command stops and uninstalls the GitLab Runner from being run as an service.
This command starts the GitLab Runner service.
This command stops the GitLab Runner service.
This command stops and then starts the GitLab Runner service.
This command prints the status of the GitLab Runner service.
By specifying the --service-name flag, it is possible to have multiple GitLab Runner services installed, with multiple separate configurations.
This command allows to fetch and process builds from GitLab.
This is main command that is executed when GitLab Runner is started as a service. It reads all defined Runners from config.toml and tries to run all of them.
The command is executed and works until it receives a signal.
It accepts the following parameters.
This is a supplementary command that can be used to run only a single build from a single GitLab instance. It doesn't use any configuration file and requires to pass all options either as parameters or environment variables. The GitLab URL and Runner token need to be specified too.
You can see all possible configuration options by using the --help flag:
This command allows you to run builds locally, trying to replicate the CI environment as much as possible. It doesn't need to connect to GitLab, instead it reads the local .gitlab-ci.yml and creates a new build environment in which all the build steps are executed.
This command is useful for fast checking and verifying .gitlab-ci.yml as well as debugging broken builds since everything is run locally.
When executing exec you need to specify the executor and the job name that is present in .gitlab-ci.yml . The command should be executed from the root directory of your Git repository that contains .gitlab-ci.yml .
gitlab-runner exec will clone the current state of the local Git repository. Make sure you have committed any changes you want to test beforehand.
For example, the following command will execute the job named tests locally using a shell executor:
To see a list of available executors, run:
To see a list of all available options for the shell executor, run:
If you want to use the docker executor with the exec command, use that in context of docker-machine shell or boot2docker shell . This is required to properly map your local directory to the directory inside the Docker container.
Limitations of gitlab-runner exec
Some of the features may or may not work, like: cache or artifacts .
gitlab-runner exec docker can only be used when Docker is installed locally. This is needed because GitLab Runner is using host-bind volumes to access the Git sources.
GitLab Runner is distributed as a single binary and contains a few internal commands that are used during builds.
Download the artifacts archive from GitLab.
Upload the artifacts archive to GitLab.
Create a cache archive, store it locally or upload it to an external server.
Restore the cache archive from a locally or externally stored file.
Below are some common pitfalls.
Access Denied when running the service-related commands
GitLab CI/CD provides a caching mechanism that can be used to save time when your jobs are running.
Caching is about speeding the time a job is executed by reusing the same content of a previous job. Use caching when you are developing software that depends on other libraries which are fetched via the internet during build time.
If caching is enabled, it's shared between pipelines and jobs at the project level by default. Caches are not shared across projects.
Make sure you read the cache reference to learn how it is defined in .gitlab-ci.yml .
Простое развертывание Prometheus на Kubernetes (CE, EES, EEP)
В данном релизе стало возможным проводить развертывание Prometheus в подключенный кластер Kubernetes в один клик, благодаря чему начать отслеживать производительность вашего приложения становится просто как никогда. Системные метрики, такие как использование процессора и памяти, передаются из Kubernetes автоматически, а ответные метрики, такие как задержка и пропускная способность доступны через NGINX ingress. Для того, чтобы начать, подключите кластер в CI/CD > Clusters .
Если у GitLab есть сетевой доступ к Prometheus, можно подключить интеграцию с Prometheus для анализа и отображения этих метрик прямо в GitLab. В следующем релизе, GitLab 10.5, интеграция будет подключена автоматически. Также она не будет требовать прямого доступа к сети, что сделает интеграцию еще более гладкой.
Share caches across different branches
To share a cache across all branches and all jobs, use the same key for everything:
To share caches between branches, but have a unique cache for each job:
Не пропустите новые возможности
Также в этом месяце мы внесли множество улучшений в эпики, мерж-реквесты, мониторинг, Geo, Runner, Git LFS, SSH и Auto DevOps.
Далее в статье мы подробнее остановимся на этих и других нововведениях GitLab 10.4.
Тестирование безопасности
Частью Complete Devops является поддержание мощных инструментов безопасности. С прошлым релизом мы выпустили статическое тестирование безопасности приложений, а в этом мы продолжаем расширять возможности безопасности, добавляя статическое тестирование для контейнеров Docker и динамическое тестирование безопасности приложений (Dynamic Application Security Testing (DAST)).
Тестирование производительности браузера теперь включено в Auto DevOps (EEP)
В прошлой версии мы добавили тестирование производительности браузера, чтобы легко определять влияние изменений на производительность веб-приложений, перед выполнением мержа. Чтобы использовать эту возможность, необходимо было добавить дополнительную работу в .gitlab-ci.yml и адаптировать ее под ваши нужды.
В GitLab 10.4 тестирование производительности браузера включено в Auto DevOps, что предоставляет автоматическую аналитику производительности корневой страницы с без какой-либо настройки.
Если вы хотите тестировать дополнительные страницы, просто добавьте соответствующие пути в файл .gitlab-urls.txt в корневой директории репозитория.
Disable cache on specific jobs
If you have defined the cache globally, it means that each job uses the same definition. You can override this behavior per-job, and if you want to disable it completely, use an empty hash:
MVP месяца — George Tsiolis
George присоединился к работе над GitLab только с прошлой версии и на протяжении последнего месяца внес серьезный вклад в улучшение интерфейса, добавив семь мерж-реквестов, в том числе фиксы иконок боковой панели и иерархии списков в пользовательских настройках.
Спасибо George за его внимательность и работу!
Очистка кэша Runner (CE, EES, EEP)
GitLab Runner использует кэш для того, чтобы ускорить исполнение за счет переиспользования существующих данных между разными работами. Но иногда это ведет к противоречивому поведению, например, когда одна работа изменяет локальную копию репозитория, и эти изменения влияют на работу следующей.
В GitLab 10.4 мы представляем новую кнопку на странице конвейеров, по нажатию на которую очищается существующий кэш для конкретного проекта, и новый начнется со свежим. Это решает проблему «грязного» запуска.
Common use cases
The most common use case of caching is to avoid downloading content like dependencies or libraries repeatedly between subsequent runs of jobs. Node.js packages, PHP packages, Ruby gems, Python libraries, and others can all be cached.
For more examples, check out our GitLab CI/CD templates.
Caching Ruby dependencies
Assuming your project is using Bundler to install the gem dependencies, the following example defines cache globally so that all jobs inherit it. Gems are installed in vendor/ruby/ and are cached per-branch:
If you have jobs that each need a different selection of gems, use the prefix keyword in the global cache definition. This configuration generates a different cache for each job.
For example, a testing job might not need the same gems as a job that deploys to production:
Деплой — deploy
Теперь осталось задеплоить артефакт на dev-сервер с помощью ssh и scp.
Не забудьте создать переменные в GitLab CI CD:
- $DEV_USER — пользователь системы, от чьего имени будет происходить деплой.
- $DEV_HOST — ip адрес сервера.
- $DEV_APP_PATH — путь до папки приложения.
- $SSH_PRIVATE_KEY — приватный ключ.
Раздел before_script отвечает за выполнение настроек перед основным скриптом. Мы проверяем наличие ssh-agent, устанавливаем его при отсутствии. После чего добавляем приватный ключ, устанавливаем правильные права на папки.
В разделе script происходит деплой на сервер:
- Проверяем наличие старого jar и переименовываем его. $CI_PIPELINE_ID — это глобальный номер сборки Pipeline.
- Копируем новый jar на сервер.
- Останавливаем и запускаем службу, отвечающую за приложение.
- Отправляем уведомление об успехе в телеграм. Об этом ниже.
На пре-прод делаем по аналогии, только меняем переменные на $PRE_PROD_* .
Сортировка списка задач в эпиках (EEU)
Эпики позволяют вам управлять набором задач, связанных общей темой. Зачастую эпик связан с разработкой большой функциональности, разделенной на несколько задач, работа над которыми ведется параллельно на множестве майлстоунов.
Сортировка списка задач в эпике может выполняться по различным критериям, в зависимости от рабочего процесса организации. Такими критериями могут быть приоритет, сложность, выполнимость (feasibility) или порядок выполнения.
В одних организациях закрытые задачи предпочитают видеть в начале списка, а в других — в конце. В данном релизе мы добавляем возможность менять порядок задач, просто перетягивая их в списке на нужное место — так же как и в досках задач.
Clearing the cache by changing cache:key
All you have to do is set a new cache: key in your .gitlab-ci.yml . In the next run of the pipeline, the cache is stored in a different location.
Бонус: уведомления о деплое в Telegram
Полезная фишка для уведомления менеджеров. После сборки в телеграм отправляется статус сборки, название проекта и ветка сборки.
В задачах деплоя последней командой пропишите:
Сам файл необходимо добавить в корень проекта, рядом с файлом .gitlab-ci.yml .
Скрипт отправляет запрос к API Telegram, через curl. Параметром скрипта передается emoji статуса билда.
Не забудьте добавить новые параметры в CI/CD:
Необходимо создать задачи для уведомления о падении сборки.
По сложившейся традиции у нас отдельная задача для прод-среды. Благодаря параметру when: on_failure задача отрабатывает только, когда одна из предыдущих завершилась неудачно.
Удобно, что теперь и код и сборка находятся в одном месте. Несмотря на недостатки GitLab CI, пользоваться им в целом удобно.
Редактор Web IDE (бета-версия) (EEU)
В GitLab 10.4 мы вводим бета-версию нового редактора Web IDE, с помощью которого можно будет проще и быстрее вносить небольшие фиксы и реагировать на обратную связь в мерж-реквестах, благодаря исчезновению необходимости stash’а изменений и локального переключения между ветками.
В будущих релизах мы планируем усилить интеграцию Web IDE с мерж-реквестами, улучшить функциональность коммита отдельных файлов, а также добавить превью и веб-терминал для того, чтобы каждый мог внести свой вклад.
Пока Web IDE находится в стадии ранней беты, доступ к нему опционален. Чтобы получить его, зайдите в ваш профиль, далее Settings > Preferences, подключите Web IDE и нажмите Save.
Share caches across the same branch
Define a cache with the key: $ so that jobs of each branch always use the same cache:
This configuration is safe from accidentally overwriting the cache, but merge requests get slow first pipelines. The next time a new commit is pushed to the branch, the cache is re-used and jobs run faster.
To enable per-job and per-branch caching:
To enable per-stage and per-branch caching:
Where the caches are stored
The runner is responsible for storing the cache, so it's essential to know where it's stored. All the cache paths defined under a job in .gitlab-ci.yml are archived in a single cache.zip file and stored in the runner's configured cache location. By default, they are stored locally in the machine where the runner is installed and depends on the type of the executor.
GitLab Runner executor | Default path of the cache |
---|---|
Shell | Locally, stored under the gitlab-runner user's home directory: /home/gitlab-runner/cache////cache.zip . |
Docker | Locally, stored under Docker volumes: /var/lib/docker/volumes//_data////cache.zip . |
Docker machine (autoscale runners) | Behaves the same as the Docker executor. |
Улучшения производительности (CE, EES, EEP)
В GitLab 10.4 мы ввели улучшения производительности для задач, мерж-реквестов, репозиториев и API. Наиболее заслуживающие внимания из них:
Подробные release notes и инструкции по обновлению/установке можно прочитать в оригинальном англоязычном посте: GitLab 10.4 released with Dynamic Application Security Testing and Web IDE (beta).
Из-за прекращения поддержи Bitbucket Setver пришлось переехать на GitLab.
В Bitbucket Server не было встроенного CI/CD, поэтому использовали Teamcity. Из-за проблемы интеграции Teamcity с GitLab, мы попробовали GitLab Pipline. И остались довольны.
Disclamer: У меня не так много опыта в CI/CD, так что статья скорее для новичков. Мы рассмотрим самый простой пример деплоя на несколько контуров с доставкой с помощью scp и запуском linux сервиса. Буду рад услышать конструктивную критику с предложениями по оптимизации скрипта сборки.
Поддержка openSUSE Leap 42.3 (CE, EES, EEP)
С выходом GitLab 10.4 пакеты Omnibus теперь доступны для openSUSE 42.3.
Этот релиз будет последним с поддержкой openSUSE 42.2, поскольку она официально прекращена.
Настройка GitLab CI для Maven
Что делать если у вас Gradle? Загляните в оригинал статьи, там я рассказываю про настройку и для Gradle. Она не сильно отличается.
Создайте в корне проекта файл .gitlab-ci.yml .
Настройку буду объяснять блоками, в конце прикреплю единый файл.
Вы можете указать нужный образ, вместо дефолтного образа у раннера.
Устанавливаем место хранения папки .m2 через переменные среды variables . Это понадобится, когда будем настраивать кэширование.
Далее указываются этапы сборки. Они позволяют группировать задачи для одновременного выполнения.
- build — стадия сборки.
- test — стадия тестирования.
- package — стадия упаковки в jar.
- deploy — стадия деплоя на сервер.
- notify — стадия уведомления о провале.
Указываем непосредственно задачи для каждой стадии.
Запуск unit тестов — test
Создаем задачу для запука тестирования.
Настройка деплоя на прод
Для прод-деплоя можно объединить сборку, тестирование и упаковку в одну задачу.
Мы защищаемся от срабатывания на ветки формата release-* , нам нужно срабатывание только по тегу.
Деплой аналогичен пре-проду, изменяется только only и переменные.
Дополнительно появляется задача с отправкой артефакта в корпоративный nexus. Деплой на сервер и в нексус работает параллельно.
Caching PHP dependencies
Assuming your project is using Composer to install the PHP dependencies, the following example defines cache globally so that all jobs inherit it. PHP libraries modules are installed in vendor/ and are cached per-branch:
Ускорение редактирования
Правило двух минут от Getting Things Done гласит: если вы можете сделать что-то за две минуты, сделайте это сейчас. Написание небольшого фикса или исправление опечатки не должно занимать много времени, однако такое редко происходит, когда нужно делать stash изменений и переключаться на другой контекст.
Излишние временные затраты при работе с фиксами негативно влияют на время цикла, что особенно заметно в географически распределенных командах — избегание git stash может привести к целым дням задержки. Новый редактор, который является первым релизом GitLab Web IDE упрощает работу с такими изменениями из интерфейса GitLab.
SAST для контейнеров Docker (EEU)
При запуске приложений из контейнеров, их код отделяется от кода остальных контейнеров на том же хосте, что повышает их безопасность. Однако даже в таких случаях безопасность приложения может подвергаться угрозам из-за проблем в среде, на которой оно запущено (например, уязвимые системные библиотеки).
В GitLab 10.4 добавлена возможность проведения проверок безопасности образа, в котором содержится ваше приложение, перед мержем изменений в стабильную ветку. Если по результатам этой проверки найдены проблемы безопасности, соответствующие предупреждения отображаются в мерж-реквесте. Такие проверки являются частью Auto DevOps.
Availability of the cache
Caching is an optimization, but it isn't guaranteed to always work. You need to be prepared to regenerate any cached files in each job that needs them.
After you have defined a cache in .gitlab-ci.yml , the availability of the cache depends on:
- The runner's executor type
- Whether different runners are used to pass the cache between jobs.
Запуск запланированного конвейера вручную (CE, EES, EEP)
Запланированные конвейеры очень удобны для запуска повторяющихся работ без участия пользователя. Обычно их используют для выполнения задач сопровождения или для создания ночных сборок вашего софта. Но иногда такие задачи необходимо выполнить немедленно и вручную, а создавать идентичное окружение (например, добавляя кастомные переменные) может быть тяжело и затратно по времени.
GitLab 10.4 дает возможность запускать запланированный конвейер вручную, прямо из веб-интерфейса: вы найдете кнопку «play» в каждом расписании в списке — и запустить конвейер можно будет всего одним кликом.
Улучшена панель производительности окружения (CE, EES, EEP)
В GitLab 10.4 мы улучшили интерфейс панели производительности окружения, которая отображает системные метрики, получаемые с помощью Prometheus.
Раньше при отслеживании метрик на определенный момент времени они находились в описании графика. Теперь эти метрики четко показаны в ховере. В следующем релизе мы добавим в описание графика общие метрики, отображая статистику вроде максимальной пропускной способности или средней задержки за определенный промежуток времени.
Улучшения Omnibus (CE, EES, EEP)
- GitLab Mattermost обновился до версии 4.5, включающей плагин Zoom для видео, аудио, расшаривания экрана и многого другого
- Сертификаты CA обновлены до 2017.09.20
- GitLab Monitor обновлен до 2.4.0
- Ruby обновлен до 2.3.6
- Библиотеки, основанные на Go — Registry, Workhorse и Prometheus — теперь собираются с Go версии 1.9.2
Что хотим получить от CI CD?
У нас на проекте было 3 контура:
- dev-сервер, на него все попадает сразу после MR;
- пре-прод-сервер, на него все попадает перед попаданием на прод, там проходит полное регресс тестирование;
- прод-сервер, собственно сама прод среда.
Что нам было необходимо от нашего CI/CD:
- Запуск unit-тестов для всех MergeRequest
- При мерже в dev ветку повторный запуск тестов и автоматический деплой на dev-сервер.
- Автоматическая сборка, тестирвоание и деплой веток формата release/* на пре-прод-сервер.
- При мерже в master ничего не происходит. Релиз собирается при обнаружении тега формата release-* . Одновременно с деплоем на прод-сервер будет происходить загрузка в корпоративный nexus.
- Бонусом настроим уведомления о статусе деплоя в Telegram.
How archiving and extracting works
This example has two jobs that belong to two consecutive stages:
If you have one machine with one runner installed, and all jobs for your project run on the same host:
- Pipeline starts.
- job A runs.
- before_script is executed.
- script is executed.
- after_script is executed.
- cache runs and the vendor/ directory is zipped into cache.zip . This file is then saved in the directory based on the runner's setting and the cache: key .
- job B runs.
- The cache is extracted (if found).
- before_script is executed.
- script is executed.
- Pipeline finishes.
By using a single runner on a single machine, you don't have the issue where job B might execute on a runner different from job A . This setup guarantees the cache can be reused between stages. It only works if the execution goes from the build stage to the test stage in the same runner/machine. Otherwise, the cache might not be available.
During the caching process, there's also a couple of things to consider:
- If some other job, with another cache configuration had saved its cache in the same zip file, it is overwritten. If the S3 based shared cache is used, the file is additionally uploaded to S3 to an object based on the cache key. So, two jobs with different paths, but the same cache key, overwrites their cache.
- When extracting the cache from cache.zip , everything in the zip file is extracted in the job's working directory (usually the repository which is pulled down), and the runner doesn't mind if the archive of job A overwrites things in the archive of job B .
It works this way because the cache created for one runner often isn't valid when used by a different one. A different runner may run on a different architecture (for example, when the cache includes binary files). Also, because the different steps might be executed by runners running on different machines, it is a safe default.
Установка Gitlab Runner
Перед установкой ранера создадим папку с конфигурацией, чтобы не приходилось для изменений лезть в контейнер.
Само создание ранера выполняется в одну команду. Можно создать сколько угодно ранеров.
Мало создать раннер, теперь его нужно зарегистрировать в GitLab. Зарегистрировать можно на уровне всего GitLab, тогда сборки будут выполняться для любого проекта; на уровне группы — выполнятся только для группы, и на уровне проекта.
Заходим в контейнер.
Отвечаем на вопросы:
- Адрес вашего gitlab.
- Токен авторизации. Посмотреть его можно в настройках гурппы/проекта в разделе CI/CD Runners.
- Название раннера.
- Теги ранера, можно пропустить нажав Enter.
- Исполнитель сборки. Вводим docker.
- Образ, который будет использоваться по умолчанию, если не установлен другой.
После этого в настройках проекта можно посмотреть доступные раннеры.
После регистрации, в папке /home/user/runner_name появится файл с настройками конфигурации config.toml . Нам нужно добавить docker volume для кэширования промежуточных результатов.
Проблема кэширования
В начале статьи я рассказал о проблеме кеширования. Ее можно решить с помощью монтирования одного volume к разным раннерам. То есть во втором своем раннере так же укажите volumes = ["gitlab-runner-cache:/cache"] . Таким образом разные раннеры будут иметь единый кэш.
В итоге файл конфигурации выглядит так:
После изменения перезапускаем раннер.
Cache vs artifacts
If you use cache and artifacts to store the same path in your jobs, the cache might be overwritten because caches are restored before artifacts.
Don't use caching for passing artifacts between stages, as it is designed to store runtime dependencies needed to compile the project:
cache : For storing project dependencies
Caches can increase the speed of a given job in subsequent pipelines. You can store downloaded dependencies so that they don't have to be fetched from the internet again. Dependencies include things like npm packages, Go vendor packages, and so on. You can configure a cache to pass intermediate build results between stages, but you should use artifacts instead.
artifacts : Use for stage results that are passed between stages.
Artifacts are files that are generated by a job so they can be stored and uploaded. You can fetch and use artifacts in jobs in later stages of the same pipeline. You can't create an artifact in a job in one stage, and use this artifact in a different job in the same stage. This data is not available in different pipelines, but can be downloaded from the UI.
If you download modules while building your application, you can declare them as artifacts and subsequent stage jobs can use them.
You can define an expiry time so artifacts are deleted after a defined time. Use dependencies to control which jobs fetch the artifacts.
Artifacts can also be used to make files available for download after a pipeline completes, like a build image.
- Are disabled if not defined globally or per job (using cache: ).
- Are available for all jobs in your .gitlab-ci.yml if enabled globally.
- Can be used in subsequent pipelines by the same job in which the cache was created (if not defined globally).
- Are stored where GitLab Runner is installed and uploaded to S3 if distributed cache is enabled.
- If defined per job, are used:
- By the same job in a subsequent pipeline.
- By subsequent jobs in the same pipeline, if they have identical dependencies.
- Are disabled if not defined per job (using artifacts: ).
- Can only be enabled per job, not globally.
- Are created during a pipeline and can be used by subsequent jobs in the same pipeline.
- Are always uploaded to GitLab (known as coordinator).
- Can have an expiration value for controlling disk usage (30 days by default).
Both artifacts and caches define their paths relative to the project directory, and can't link to files outside it.
Good caching practices
To ensure maximum availability of the cache, when you declare cache in your jobs, use one or more of the following:
- Tag your runners and use the tag on jobs that share their cache.
- Use sticky runners that are only available to a particular project.
- Use a key that fits your workflow (for example, different caches on each branch). For that, you can take advantage of the predefined CI/CD variables.
For runners to work with caches efficiently, you must do one of the following:
Read about the availability of the cache to learn more about the internals and get a better idea how cache works.
Кластеры GitLab теперь общедоступны (CE, EES, EEP)
Мы с гордостью сообщаем, что в версии GitLab 10.4 интеграция с кластером Kubernetes стала общедоступна. Вы можете присоединить ваши существующие кластеры к вашему проекту или создать новые с помощью Google Kubernetes Engine (GKE) парой кликов мыши на новой странице кластеров в разделе CI/CD.
Старый сервис интеграции с Kubernetes все еще доступен, но его использование возможно, только если он был включен до обновления GitLab до 10.4. В следующих релизах существующие данные будут перенесены на новую страницу кластеров, а страница интеграции в конечном итоге будет удалена. Шаблоны сервиса, доступные из зоны администратора, работают как и прежде.
Clearing the cache
Runners use cache to speed up the execution of your jobs by reusing existing data. This however, can sometimes lead to an inconsistent behavior.
To start with a fresh copy of the cache, there are two ways to do that.
Cache Node.js dependencies
If your project is using npm to install the Node.js dependencies, the following example defines cache globally so that all jobs inherit it. By default, npm stores cache data in the home folder ~/.npm but you can't cache things outside of the project directory. Instead, we tell npm to use ./.npm , and cache it per-branch:
Упаковка — package
Следом добавляем задачу упаковки с выключенными тестами. Она уже выполняется только для веток dev и release/* . Упаковывать Merge Request смысла нет.
Обратите внимание на policy: pull и artifacts . В следующих задачах не нужны исходники и зависимости, так что policy: pull отключает кэширование. Для сохранения результатов сборки используем artifacts , который сохраняет .jar файлы и передает их следующим задачам.
Артефакты
Помимо кэша между сборками можно передавать артефакты.
Артефакт — это файлы, которые считаются законченным продуктом сборки. Например .jar файлы приложения.
В отличие от кэша, артефакт передается между раннерами. Из-за этого многие злоупотребляют использованием артефактов там, где стоит использовать кэш.
Следуйте следующим правилам:
- Если текущее задание может выполняться самостоятельно, но в присутствии контента работа будет идти быстрее, используйте кэш.
- Если текущее задание зависит от результатов предыдущего, то есть не может выполняться само по себе, используйте артефакты и зависимости.
Иконка статуса для файлов, отслеживаемых LFS (CE, EES, EEP)
Определяйте, какие файлы отслеживаются Git LFS, с помощью новой иконки статуса отслеживания LFS. Эта иконка отображается в блобах и в списках файлов, включая список изменений мерж-реквестов. Это дает возможность проверять, корректно ли LFS отслеживает бинарные файлы при просмотре мерж-реквеста.
Clearing the cache manually
If you want to avoid editing .gitlab-ci.yml , you can clear the cache via the GitLab UI:
Navigate to your project's CI/CD > Pipelines page.
Click on the Clear runner caches button to clean up the cache.
On the next push, your CI/CD job uses a new cache.
NOTE: Each time you clear the cache manually, the internal cache name is updated. The name uses the format cache- , and the index increments by one each time. The old cache is not deleted. You can manually delete these files from the runner storage.
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Caching in GitLab CI/CD (FREE)
A cache is one or more files a job downloads and saves. Subsequent jobs that use the same cache don't have to download the files again, so they execute more quickly.
To learn how to define the cache in your .gitlab-ci.yml file, see the cache reference.
How cache is different from artifacts
Use cache for dependencies, like packages you download from the internet. Cache is stored where GitLab Runner is installed and uploaded to S3 if distributed cache is enabled.
Use artifacts to pass intermediate build results between stages. Artifacts are generated by a job, stored in GitLab, and can be downloaded.
Both artifacts and caches define their paths relative to the project directory, and can't link to files outside it.
- Define cache per job by using the cache keyword. Otherwise it is disabled.
- Subsequent pipelines can use the cache.
- Subsequent jobs in the same pipeline can use the cache, if the dependencies are identical.
- Different projects cannot share the cache.
- Protected and non-protected branches do not share the cache.
- Define artifacts per job.
- Subsequent jobs in later stages of the same pipeline can use artifacts.
- Different projects cannot share artifacts.
- Artifacts expire after 30 days by default. You can define a custom expiration time.
- The latest artifacts do not expire if keep latest artifacts is enabled.
- Use dependencies to control which jobs fetch the artifacts.
Good caching practices
To ensure maximum availability of the cache, do one or more of the following:
-
and use the tag on jobs that share the cache. . that fits your workflow. For example, you can configure a different cache for each branch.
For runners to work with caches efficiently, you must do one of the following:
Use multiple caches
You can have a maximum of four caches:
If multiple caches are combined with a fallback cache key, the fallback cache is fetched every time a cache is not found.
Use a fallback cache key
You can use the $CI_COMMIT_REF_SLUG predefined variable to specify your cache:key . For example, if your $CI_COMMIT_REF_SLUG is test , you can set a job to download cache that's tagged with test .
If a cache with this tag is not found, you can use CACHE_FALLBACK_KEY to specify a cache to use when none exists.
In the following example, if the $CI_COMMIT_REF_SLUG is not found, the job uses the key defined by the CACHE_FALLBACK_KEY variable:
Disable cache for specific jobs
If you define the cache globally, each job uses the same definition. You can override this behavior for each job.
To disable it completely for a job, use an empty hash:
Inherit global configuration, but override specific settings per job
You can override cache settings without overwriting the global cache by using anchors. For example, if you want to override the policy for one job:
For more information, see cache: policy .
Common use cases for caches
Usually you use caches to avoid downloading content, like dependencies or libraries, each time you run a job. Node.js packages, PHP packages, Ruby gems, Python libraries, and others can be cached.
Share caches between jobs in the same branch
To have jobs in each branch use the same cache, define a cache with the key: $CI_COMMIT_REF_SLUG :
This configuration prevents you from accidentally overwriting the cache. However, the first pipeline for a merge request is slow. The next time a commit is pushed to the branch, the cache is re-used and jobs run faster.
To enable per-job and per-branch caching:
To enable per-stage and per-branch caching:
Share caches across jobs in different branches
To share a cache across all branches and all jobs, use the same key for everything:
To share a cache between branches, but have a unique cache for each job:
Cache Node.js dependencies
If your project uses npm to install Node.js dependencies, the following example defines cache globally so that all jobs inherit it. By default, npm stores cache data in the home folder ( ~/.npm ). However, you can't cache things outside of the project directory. Instead, tell npm to use ./.npm , and cache it per-branch:
Compute the cache key from the lock file
You can use cache:key:files to compute the cache key from a lock file like package-lock.json or yarn.lock , and reuse it in many jobs.
If you're using Yarn, you can use yarn-offline-mirror to cache the zipped node_modules tarballs. The cache generates more quickly, because fewer files have to be compressed:
Cache PHP dependencies
If your project uses Composer to install PHP dependencies, the following example defines cache globally so that all jobs inherit it. PHP libraries modules are installed in vendor/ and are cached per-branch:
Cache Python dependencies
If your project uses pip to install Python dependencies, the following example defines cache globally so that all jobs inherit it. Python libraries are installed in a virtual environment under venv/ . pip's cache is defined under .cache/pip/ and both are cached per-branch:
Cache Ruby dependencies
If your project uses Bundler to install gem dependencies, the following example defines cache globally so that all jobs inherit it. Gems are installed in vendor/ruby/ and are cached per-branch:
If you have jobs that need different gems, use the prefix keyword in the global cache definition. This configuration generates a different cache for each job.
For example, a testing job might not need the same gems as a job that deploys to production:
Cache Go dependencies
If your project uses Go Modules to install Go dependencies, the following example defines cache in a go-cache template, that any job can extend. Go modules are installed in $/pkg/mod/ and are cached for all of the go projects:
Availability of the cache
Caching is an optimization, but it isn't guaranteed to always work. You might need to regenerate cached files in each job that needs them.
After you define a cache in .gitlab-ci.yml , the availability of the cache depends on:
- The runner's executor type.
- Whether different runners are used to pass the cache between jobs.
Where the caches are stored
All caches defined for a job are archived in a single cache.zip file. The runner configuration defines where the file is stored. By default, the cache is stored on the machine where GitLab Runner is installed. The location also depends on the type of executor.
Runner executor Default path of the cache Shell Locally, under the gitlab-runner user's home directory: /home/gitlab-runner/cache////cache.zip . Docker Locally, under Docker volumes: /var/lib/docker/volumes//_data////cache.zip . Docker Machine (autoscale runners) The same as the Docker executor. If you use cache and artifacts to store the same path in your jobs, the cache might be overwritten because caches are restored before artifacts.
Cache key names
A suffix is added to the cache key, with the exception of the fallback cache key.
As an example, assuming that cache.key is set to $CI_COMMIT_REF_SLUG , and that we have two branches main and feature , then the following table represents the resulting cache keys:
Branch name Cache key main main-protected feature feature-non_protected How archiving and extracting works
This example shows two jobs in two consecutive stages:
If one machine has one runner installed, then all jobs for your project run on the same host:
- Pipeline starts.
- job A runs.
- before_script is executed.
- script is executed.
- after_script is executed.
- cache runs and the vendor/ directory is zipped into cache.zip . This file is then saved in the directory based on the runner's setting and the cache: key .
- job B runs.
- The cache is extracted (if found).
- before_script is executed.
- script is executed.
- Pipeline finishes.
By using a single runner on a single machine, you don't have the issue where job B might execute on a runner different from job A . This setup guarantees the cache can be reused between stages. It only works if the execution goes from the build stage to the test stage in the same runner/machine. Otherwise, the cache might not be available.
During the caching process, there's also a couple of things to consider:
- If some other job, with another cache configuration had saved its cache in the same zip file, it is overwritten. If the S3 based shared cache is used, the file is additionally uploaded to S3 to an object based on the cache key. So, two jobs with different paths, but the same cache key, overwrites their cache.
- When extracting the cache from cache.zip , everything in the zip file is extracted in the job's working directory (usually the repository which is pulled down), and the runner doesn't mind if the archive of job A overwrites things in the archive of job B .
It works this way because the cache created for one runner often isn't valid when used by a different one. A different runner may run on a different architecture (for example, when the cache includes binary files). Also, because the different steps might be executed by runners running on different machines, it is a safe default.
Clearing the cache
Runners use cache to speed up the execution of your jobs by reusing existing data. This can sometimes lead to inconsistent behavior.
There are two ways to start with a fresh copy of the cache.
Clear the cache by changing cache:key
Change the value for cache: key in your .gitlab-ci.yml file. The next time the pipeline runs, the cache is stored in a different location.
Clear the cache manually
You can clear the cache in the GitLab UI:
- On the top bar, select Menu > Projects and find your project.
- On the left sidebar, select CI/CD > Pipelines.
- In the top right, select Clear runner caches.
On the next commit, your CI/CD jobs use a new cache.
NOTE: Each time you clear the cache manually, the internal cache name is updated. The name uses the format cache- , and the index increments by one. The old cache is not deleted. You can manually delete these files from the runner storage.
If you have a cache mismatch, follow these steps to troubleshoot.
Reason for a cache mismatch How to fix it You use multiple standalone runners (not in autoscale mode) attached to one project without a shared cache. Use only one runner for your project or use multiple runners with distributed cache enabled. You use runners in autoscale mode without a distributed cache enabled. Configure the autoscale runner to use a distributed cache. The machine the runner is installed on is low on disk space or, if you've set up distributed cache, the S3 bucket where the cache is stored doesn't have enough space. Make sure you clear some space to allow new caches to be stored. There's no automatic way to do this. You use the same key for jobs where they cache different paths. Use different cache keys so that the cache archive is stored to a different location and doesn't overwrite wrong caches. Cache mismatch example 1
If you have only one runner assigned to your project, the cache is stored on the runner's machine by default.
If two jobs have the same cache key but a different path, the caches can be overwritten. For example:
- job A runs.
- public/ is cached as cache.zip.
- job B runs.
- The previous cache, if any, is unzipped.
- vendor/ is cached as cache.zip and overwrites the previous one.
- The next time job A runs it uses the cache of job B which is different and thus isn't effective.
To fix this issue, use different keys for each job.
Cache mismatch example 2
In this example, you have more than one runner assigned to your project, and distributed cache is not enabled.
The second time the pipeline runs, you want job A and job B to re-use their cache (which in this case is different):
Even if the key is different, the cached files might get "cleaned" before each stage if the jobs run on different runners in subsequent pipelines.
В первом релизе 2018 года мы внесли улучшения в процессы планирования, тестирования, развертывания и работы с мерж-реквестами. Кроме того, в данный релиз включены новые возможности тестирования безопасности, а также первая версия Web IDE, который является частью нашего амбициозного проекта Complete DevOps.
Caching Go dependencies
Assuming your project is using Go Modules to install Go dependencies, the following example defines cache in a go-cache template, that any job can extend. Go modules are installed in $/pkg/mod/ and are cached for all of the go projects:
Коротко о Gitlab Pipline
Если говорить простыми словами: сборка делится на задачи. Какие-то задачи выполняются последовательно и передают результаты следующим задачам, какие-то задачи распаралеливаются: например можно одновременно деплоить на сервер и в nexus.
Не обязательно один раннер отвечает за все задачи в сборке. Если на проекте два раннера, то первую задачу может взять один ранер, после ее выполнения вторую задачу возьмет другой раннер.
Раннеры бывают разных типов. Мы рассмотрим executor docker. Для каждой задачи создается новый чистый контейнер. Но между контейнерами можно передавать промежуточные результаты — это называется кэширование.
Перебазирование и перемотка в CE (CE, EES, EEP)
В GitLab CE стало возможным делать перебазирование (rebase) и перемотку (fast-forward) мержа прямо из интерфейса мерж-реквеста. Теперь для этого не нужно переключаться между GitLab и командной строкой; все это можно сделать внутри GitLab.
Ранее эта функциональность была доступна только в EE. Мы добавили ее в CE как следствие добавления GNOME в GitLab CE.
API групповых досок задач (EEP)
Начиная с данного релиза стало возможным управлять групповыми досками задач через API таким же образом, как и проектными досками задач. Это нововведение добавляет новые возможности автоматизации и повышает гибкость управления рабочими процессами вашей команды.
К примеру, у некоторых команд есть бизнес требования по автоматическому перемещению задач между рядами доски в ответ на выполнение определенных условий. Теперь это можно настроить и для групповых досок задач через API.
Поддержка GitLab Geo для HA теперь общедоступна (EEP)
В GitLab 10.2 и Geo, и Postgres HA по отдельности стали общедоступными, но использовать Geo вместе с HA можно было только в бета-версии.
Конфигурации, использующие GitLab Geo вместе с HA теперь общедоступны. Это позволит распределенным командам наслаждаться повышенной скоростью fetch-операций Git при использовании GitLab Geo и избыточности высокодоступных конфигураций.
Caching Python dependencies
Assuming your project is using pip to install the Python dependencies, the following example defines cache globally so that all jobs inherit it. Python libraries are installed in a virtual environment under venv/ , pip's cache is defined under .cache/pip/ and both are cached per-branch:
Inherit global configuration, but override specific settings per job
You can override cache settings without overwriting the global cache by using anchors. For example, if you want to override the policy for one job:
For more fine tuning, read also about the cache: policy .
API эпиков (EEU)
Начиная с данной версии, GitLab API поддерживает эпики. Теперь вы можете управлять отдельными эпиками, их списками и всеми их атрибутами (название, описание и даты) через API, что позволит вашей команде создавать кастомные и/или автоматизированные рабочие процессы вне GitLab.
Также поддерживается управление списками задач эпика, в том числе изменение порядка их отображения.
Быстрый поиск ключа SSH в CE (CE, EES, EEP)
При авторизации пользователя OpenSSH использует линейный поиск, чтобы найти ключ. Это значит, что SSH операции становятся медленнее, когда растет число пользователей инстанса GitLab. Для больших инстансов при выполнении запроса может потребоваться значительное время и высокая скорость записи на диск, что замедлит использование Git по SSH.
В GitLab 9.3 в GitLab EE был добавлен быстрый поиск ключа SSH. Это позволяет пользователям авторизоваться с помощью быстрого индексированного поиска в базе данных GitLab вместо медленного линейного поиска, который был по умолчанию. GitLab CE делается для небольших команд, поэтому предыдущие версии не включали эту оптимизацию. Однако, для поддержки Cloud Native Helm Charts в GitLab, все части кода должны поддерживать быстрый поиск ключей SSH — поэтому мы добавили эту возможность и в GitLab CE.
Кэширование и его особенности
Механизм кэширования разрабатывал какой-то одаренный человек. Поэтому сразу разобраться, как оно работает, будет не просто. В отдельной статье можно прочитать о кэшировании подробнее.
Каждый раннер хранит кэш в папке /cache . Для каждого проекта в этой папке создается еще папка. Сам кэш хранится в виде zip архива.
Можно определить только один набор папок для кэша. Также только для всего набора можно выбрать политику кэширования. Например если вы уверены, что задача не изменит кэш, то можно его не загружать. Но нельзя запретить загружать например две папки из четырех.
Нет возможности установить глобальный кэш и добавить к нему дополнительные папки для конкретных задач.
Так же стоит знать, что кэш не удаляется после окончания сборки. При следующей такой же сборке старый кэш будет доступен.
Эти особенности усложняют создание инструкций для CI CD.
Cache mismatch
In the following table, you can see some reasons where you might hit a cache mismatch and a few ideas how to fix it.
Reason of a cache mismatch How to fix it You use multiple standalone runners (not in autoscale mode) attached to one project without a shared cache Use only one runner for your project or use multiple runners with distributed cache enabled You use runners in autoscale mode without a distributed cache enabled Configure the autoscale runner to use a distributed cache The machine the runner is installed on is low on disk space or, if you've set up distributed cache, the S3 bucket where the cache is stored doesn't have enough space Make sure you clear some space to allow new caches to be stored. There's no automatic way to do this. You use the same key for jobs where they cache different paths. Use different cache keys to that the cache archive is stored to a different location and doesn't overwrite wrong caches. Let's explore some examples.
Examples
Let's assume you have only one runner assigned to your project, so the cache is stored in the runner's machine by default.
Two jobs could cause caches to be overwritten if they have the same cache key, but they cache a different path:
- job A runs.
- public/ is cached as cache.zip.
- job B runs.
- The previous cache, if any, is unzipped.
- vendor/ is cached as cache.zip and overwrites the previous one.
- The next time job A runs it uses the cache of job B which is different and thus isn't effective.
To fix that, use different keys for each job.
In another case, let's assume you have more than one runner assigned to your project, but the distributed cache is not enabled. The second time the pipeline is run, we want job A and job B to re-use their cache (which in this case is different):
Even if the key is different, the cached files might get "cleaned" before each stage if the jobs run on different runners in the subsequent pipelines.
GitLab Runner 10.4 (CE, EES, EEP)
Также в этом релизе мы выпускаем GitLab Runner 10.4! GitLab Runner — проект с открытым исходным кодом, который используется для запуска работ CI/CD и отправления результатов обратно в GitLab.
Самые важные изменения:
Полный список изменений вы найдете в CHANGELOG GitLab Runner
Динамическое тестирование безопасности приложений (DAST) (EEU)
Проведение статических проверок кода — первый шаг к обнаружению потенциальных уязвимостей в его безопасности. Однако, после развертывания ваше приложение подвергается риску другой категории атак, например, с использованием межсайтовых скриптов или ненадежной аутентификации.
Мы продолжаем работу над автоматическим обнаружением проблем безопасности и добавляем в GitLab 10.4 систему динамического тестирования безопасности приложений (Dynamic Application Security Testing (DAST)). С ее помощью можно проверить живую версию приложения (например, Review App, созданный в предыдущей работе) прямо из конвейера CI/CD. Начиная с GitLab 10.4.1 Auto DevOps будет автоматически запускать DAST для Review Apps ваших приложений.
Сборка — Build
Раздел script выполняет linux команды.
Переменная GitLab CI/CD $MAVEN_SETTINGS необходима для передачи файла settings.xml , если вы используете нестандартные настройки, например корпоративные репозитории. Переменная создается в настройках CI/CD для группы/проекта. Тип переменной File.
Раздел only указывает для каких веток и тегов выполнять задачу. Чтобы не собирать каждую запушенную ветку устанавливаем: dev , merge_requests и ветки формата /release/* .
Раздел only не разделяет ветка это или тег. Поэтому мы указываем параметр except , который исключает теги. Из-за этого поведения за сборку на прод отвечают отдельные задачи. В противном случае, если бы кто-то создал тег формата release/* , то он бы запустил сборку.
Для защиты от случайного деплоя в прод джуном, рекомендую установить защиту на ветки dev , master , /release/* , а так же на теги release-* . Делается это в настройках проекта GitLab.
Раздел cache отвечает за кэширование. Чтобы каждый раз не выкачивать зависимости добавляем в кэш папку ./target и ./.m2 .
Читайте также:
- Почему вк не работает на компьютере сегодня
- Влияние компьютера на психику человека
- Silver schmidt pc тип n электронный молоток для испытаний бетона с подключением к компьютеру поверен
- Некоторые извлеченные файлы изменились хотите добавить их в архив
- Служба смарт карт не запущена на компьютере к которому подключен рутокен