Open
Issue created Dec 03, 2018 by
ERROR: Could not create cache adapter
Summary
When running the job, this error come up. Nevertheless, the job finishes with success.
Version 11.5 -> ERROR: Could not create cache adapter
error=cache factory not found: factory for cache adapter «» was not registered
Steps to reproduce
- It happens with any job in the gitlab-ci.yml, for example:
.cache_assets: &cache_assets
stage: cache
script:
- cd client
- yarn install
- yarn run dist
artifacts:
paths:
- client/dist
when: on_success
expire_in: 1 days
-
In the runner console, I will get:
error=cache factory not found: factory for cache adapter "" was not registered
-
The job finishes as expected and cache folder is created.
Expected behavior
This error should not appear.
Environment description
This is the toml description:
[[runners]]
name = "name-of-the-runner"
url = "https://gitlab.com/"
token = "XXXXXX"
executor = "docker"
shell = "bash"
cache_dir = "/home/cache"
[runners.docker]
tls_verify = false
image = "image/image.1.0"
privileged = false
disable_cache = false
volumes = ["/home/aks:/root/.kube/", "/home/cache:/cache:rw", "/var/run/docker.sock:/var/run/docker.sock"]
shm_size = 268435456
[runners.cache]
[runners.cache.s3]
[runners.cache.gcs]
Used GitLab Runner version
Version: 11.5.0
Git revision: 3afdaba6
Git branch: 11-5-stable
GO version: go1.8.7
Built: 2018-11-22T09:20:06+0000
OS/Arch: linux/amd64
Bug Investigation and analysis tasks: workflowrefinement
- Setup test environment.
- Attempt to reproduce the bug.
- If bug can be reproduced, analyze logs and determine the possible root cause.
- Update the proposal section in the desription with the proposed fix, including a note on level of effort.
Proposed fix
{placeholder}
Edited Dec 01, 2022 by Katrin Leinweber
GitLab Runner: Cache adapter could not be initialized: missing S3 configuration
Some day gitlab runner cache just stop work. Version gitlab-runner=12.0.1
No URL provided, cache will not be downloaded from shared cache server. Instead a local version of cache will be extracted.
Sep 3 13:32:29 review gitlab-runner[354]: ERROR: Could not create cache adapter error=cache adapter could not be initialized: missing S3 configuration
Old configuration
[[runners]] name = "review" url = "https://gitlabserver:443/ci/" token = "token" executor = "shell" output_limit = 12288 builds_dir = "/data/builds" cache_dir = "/data/cache" [runners.cache] Type = "s3" ServerAddress = "s3.amazonaws.com" AccessKey = "AccessKey" SecretKey = "SecretKey" BucketName = "BucketName" BucketLocation = "eu-central-1" Insecure = false Path = "cache" Shared = true
With GitLab Runner 11.3.0, the configuration parameters related to S3 were moved to a dedicated [runners.cache.s3] section. The old format of the configuration with S3 configured directly in [runners.cache] was deprecated with GitLab Runner 11.3.0. With GitLab Runner 12.0.0 the old configuration syntax was removed and is no longer supported.
We need just change configuration in /etc/gitlab-runner/config.toml to
[[runners]] name = "review" url = "https://gitlabserver:443/ci/" token = "token" executor = "shell" output_limit = 12288 builds_dir = "/data/builds" cache_dir = "/data/cache" [runners.cache] Type = "s3" Path = "cache" Shared = true [runners.cache.s3] ServerAddress = "s3.amazonaws.com" AccessKey = "AccessKey" SecretKey = "SecretKey" BucketName = "BucketName" BucketLocation = "eu-central-1" Insecure = false
Work perfect with gitlab-runner=12.2.0
Popular posts from this blog
FreeRadius and Google Workspace LDAP
This is the first time when I used FreeRadius, this program reminds me of Postfix, I mean similar complicated and powerful tool. Only one big difference — very bad documentation and not enough examples. In the maillists a lot of questions without answers from FreeRadius guru. Here I provided examples of how I solved some problems or where I took too much time…
Docker persistent MAC address generation problem
When I was try start 150+ docker containers with docker-compose I found strange problem: «Could not generate persistent MAC address»
Пытаюсь запустить сборку через gitlab-runner docker:
$ gitlab-runner exec docker build:deb
ERRO[0000] Docker executor: prebuilt image helpers will be loaded from /var/lib/gitlab-runner.
Running with gitlab-runner 11.2.0 (11.2.0)
Using Docker executor with image debian:buster ...
ERROR: Preparation failed: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: "gitlab-runner-cache": executable file not found in $PATH": unknown (executor_docker.go:412:0s)
Will be retried in 3s ...
Using Docker executor with image debian:buster ...
ERROR: Preparation failed: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: "gitlab-runner-cache": executable file not found in $PATH": unknown (executor_docker.go:412:0s)
Will be retried in 3s ...
Using Docker executor with image debian:buster ...
ERROR: Preparation failed: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: "gitlab-runner-cache": executable file not found in $PATH": unknown (executor_docker.go:412:0s)
Will be retried in 3s ...
ERROR: Job failed (system failure): Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: "gitlab-runner-cache": executable file not found in $PATH": unknown (executor_docker.go:412:0s)
FATAL: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: "gitlab-runner-cache": executable file not found in $PATH": unknown (executor_docker.go:412:0s)
Содержимое .gitlab-ci.yml:
stages:
- build
build:deb:
stage: build
image: debian:buster
tags:
- deb
before_script:
- mkdir build && cd build
- apt install cmake
script:
- cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_EXPORT_COMPILE_COMMANDS=On -DRA_STATIC_LINK=ON ..
- cmake --build . -- -j 8
artifacts:
paths:
- build/run
Как исправить ошибку?
У меня не получается настроить каталог кеша, но почему-то не получается. Я даже не уверен, что для этого нужен файл config.toml.
Мой конфиг.томл:
concurrent = 1
check_interval = 0
[session_server]
session_timeout = 1800
[[runners]]
cache_dir = /tmp/gitlab-runner-cache
… как в /etc/gitlab-runner/config.toml, так и в ~/.gitlab-runner/config.toml
Мой .gitlab-ci.yml:
image: docker:latest
services:
- docker:dind
cache:
key: "myCache"
paths:
- ${CI_PROJECT_DIR]/.m2/
variables:
DOCKER_DRIVER: overlay
MAVEN_OPTS: -Dmaven.repo.local=${CI_PROJECT_DIR}/.m2
stages:
- build
- acceptance
maven-build:
image: maven:3.3-jdk-8
stage: build
script: "mvn clean package"
artifacts:
paths:
- target/*.jar
maven-acceptance:
dependencies:
- maven-build
image: maven:3.3-jdk-8
stage: acceptance
script: "mvn verify"
Когда я пытаюсь: gitlab-runner exec shell maven-build
Я получаю сообщение об ошибке:
ERROR: Could not create cache adapter error=cache factory not found: factory for cache adapter "" was not registered
Сборка прошла успешно, но репозиторий .m2 не кэшируется…
Поэтому у меня есть 2 вопроса:
- Как узнать, действительно ли gitlab-runner берет мой config.yml?
- Что такое правильная конфигурация для кэширования?
Заранее спасибо!
2 ответа
Я столкнулся с той же проблемой только сейчас. Я не уверен, какую версию Gitlab вы используете, но версия 12 поддерживает либо хранилище, совместимое с S3, либо GCS в качестве поставщика кеша (см. эти документы), но нет папки локального кэша, например cache_dir = /tmp/gitlab-runner-cache
.
Проблема заключалась в том, что я забыл добавить Type = "s3"
в раздел [runners.cache]
конфигурации Runner:
[runners.cache]
Type = "s3"
Shared = true
[runners.cache.s3]
ServerAddress = ...
6
Kevin Woblick
5 Дек 2019 в 18:05
У меня была такая же ошибка («кеш-фабрика не найдена»), и проблема заключалась в том, что значение cache_dir
не было включено в конфигурацию [runners.docker]
/ volumes
.
документ о cache_dir
говорит:
Если используется исполнитель docker, этот каталог необходимо включить в его параметр Volumes.
После добавления пути к volumes
кеш работает без S3 или другого распределенного кеша.
Вот соответствующие части рабочего /etc/gitlab-runner/config.toml
:
[[runners]]
executor = "docker"
cache_dir = "/home/gitlab-runner/cache"
[runners.docker]
volumes = ["/cache", "/home/gitlab-runner/cache"]
0
Michaël Witrant
20 Апр 2022 в 19:31
stage | group | info |
---|---|---|
Verify |
Pipeline Authoring |
To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/product/ux/technical-writing/#assignments |
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.
Cache
- 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.
- By default, protected and non-protected branches do not share the cache. However, you can change this behavior.
Artifacts
- 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:
- Tag your runners and use the tag on jobs
that share the cache. - Use runners that are only available to a particular project.
- Use a
key
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 a single runner for all your jobs.
- Use multiple runners that have
distributed caching,
where the cache is stored in S3 buckets. Shared runners on GitLab.com behave this way. These runners can be in autoscale mode,
but they don’t have to be. - Use multiple runners with the same architecture and have these runners
share a common network-mounted directory to store the cache. This directory should use NFS or something similar.
These runners must be in autoscale mode.
Use multiple caches
- Introduced in GitLab 13.10.
- Feature Flag removed, in GitLab 13.12.
You can have a maximum of four caches:
test-job: stage: build cache: - key: files: - Gemfile.lock paths: - vendor/ruby - key: files: - yarn.lock paths: - .yarn-cache/ script: - bundle config set --local path 'vendor/ruby' - bundle install - yarn install --cache-folder .yarn-cache - echo Run tests...
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
Introduced in GitLab Runner 13.4.
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:
variables: CACHE_FALLBACK_KEY: fallback-key job1: script: - echo cache: key: "$CI_COMMIT_REF_SLUG" paths: - binaries/
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:
cache: &global_cache key: $CI_COMMIT_REF_SLUG paths: - node_modules/ - public/ - vendor/ policy: pull-push job: cache: # inherit all global cache settings <<: *global_cache # override the policy policy: pull
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.
For examples, see the GitLab CI/CD templates.
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
:
cache: 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:
cache: key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
To enable per-stage and per-branch caching:
cache: key: "$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG"
Share caches across jobs in different branches
To share a cache across all branches and all jobs, use the same key for everything:
cache: key: one-key-to-rule-them-all
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:
# # https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/Nodejs.gitlab-ci.yml # image: node:latest # Cache modules in between jobs cache: key: $CI_COMMIT_REF_SLUG paths: - .npm/ before_script: - npm ci --cache .npm --prefer-offline test_async: script: - node ./specs/start.js ./specs/async.spec.js
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.
# Cache modules using lock file cache: key: files: - package-lock.json paths: - .npm/
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:
job: script: - echo 'yarn-offline-mirror ".yarn-cache/"' >> .yarnrc - echo 'yarn-offline-mirror-pruning true' >> .yarnrc - yarn install --frozen-lockfile --no-progress cache: key: files: - yarn.lock paths: - .yarn-cache/
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:
# # https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/PHP.gitlab-ci.yml # image: php:7.2 # Cache libraries in between jobs cache: key: $CI_COMMIT_REF_SLUG paths: - vendor/ before_script: # Install and run Composer - curl --show-error --silent "https://getcomposer.org/installer" | php - php composer.phar install test: script: - vendor/bin/phpunit --configuration phpunit.xml --coverage-text --colors=never
Cache Python dependencies
If your project uses pip to install
Python dependencies, the following example defines cache
globally so that
all jobs inherit it. pip’s cache is defined under .cache/pip/
and is cached per-branch:
# # https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/Python.gitlab-ci.yml # image: python:latest # Change pip's cache directory to be inside the project directory since we can # only cache local items. variables: PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip" # Pip's cache doesn't store the python packages # https://pip.pypa.io/en/stable/reference/pip_install/#caching cache: paths: - .cache/pip before_script: - python -V # Print out python version for debugging - pip install virtualenv - virtualenv venv - source venv/bin/activate test: script: - python setup.py test - pip install flake8 - flake8 .
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:
# # https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/Ruby.gitlab-ci.yml # image: ruby:2.6 # Cache gems in between builds cache: key: $CI_COMMIT_REF_SLUG paths: - vendor/ruby before_script: - ruby -v # Print out ruby version for debugging - bundle config set --local path 'vendor/ruby' # The location to install the specified gems to - bundle install -j $(nproc) # Install dependencies into ./vendor/ruby rspec: script: - rspec spec
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: key: files: - Gemfile.lock prefix: $CI_JOB_NAME paths: - vendor/ruby test_job: stage: test before_script: - bundle config set --local path 'vendor/ruby' - bundle install --without production script: - bundle exec rspec deploy_job: stage: production before_script: - bundle config set --local path 'vendor/ruby' # The location to install the specified gems to - bundle install --without test script: - bundle exec deploy
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 ${GOPATH}/pkg/mod/
and
are cached for all of the go
projects:
.go-cache: variables: GOPATH: $CI_PROJECT_DIR/.go before_script: - mkdir -p .go cache: paths: - .go/pkg/mod/ test: image: golang:1.13 extends: .go-cache script: - go test ./... -v -short
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/<user>/<project>/<cache-key>/cache.zip . |
Docker | Locally, under Docker volumes: /var/lib/docker/volumes/<volume-id>/_data/<user>/<project>/<cache-key>/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
Introduced in GitLab 15.0.
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 |
Use the same cache for all branches
Introduced in GitLab 15.0.
If you do not want to use cache key names,
you can have all branches (protected and unprotected) use the same cache.
The cache separation with cache key names is a security feature
and should only be disabled in an environment where all users with Developer role are highly trusted.
To use the same cache for all branches:
- On the top bar, select Main menu > Projects and find your project.
- On the left sidebar, select Settings > CI/CD.
- Expand General pipelines.
- Clear the Use separate caches for protected branches checkbox.
- Select Save changes.
How archiving and extracting works
This example shows two jobs in two consecutive stages:
stages: - build - test before_script: - echo "Hello" job A: stage: build script: - mkdir vendor/ - echo "build" > vendor/hello.txt cache: key: build-cache paths: - vendor/ after_script: - echo "World" job B: stage: test script: - cat vendor/hello.txt cache: key: build-cache paths: - vendor/
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 thevendor/
directory is zipped intocache.zip
.
This file is then saved in the directory based on the
runner’s setting and thecache: 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 ofjob A
overwrites
things in the archive ofjob 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 Main menu > Projects and find your project.
- On the left sidebar, select CI/CD > Pipelines.
- In the upper 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-<index>
, and the index increments by one. The old cache is not deleted. You can manually delete these files from the runner storage.
Troubleshooting
Cache mismatch
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:
stages: - build - test job A: stage: build script: make build cache: key: same-key paths: - public/ job B: stage: test script: make test cache: key: same-key paths: - vendor/
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 ofjob 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):
stages: - build - test job A: stage: build script: build cache: key: keyA paths: - vendor/ job B: stage: test script: test cache: key: keyB paths: - vendor/
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.
Если вы работаете с системой непрерывной интеграции GitLab CI, то в какой-то момент захотите использовать кэш для обмена контентом между заданиями. Но в этой децентрализованной системе сложно понять, где и как настраивать обмен контентом, а само понятие кэша частично накладывается на понятие артефактов задачи, что может ввести в ступор.
Мы перевели статью Мэтью Фронтона, которая поможет решить эту непростую задачу. Автор пробовал разные варианты на своих хост-машинах, в раннерах и проектах, а по итогу экспериментов составил краткое визуальное руководство.
Предисловие: кэш и артефакты
Концепции кэша и артефактов выглядят похожими, потому что в обоих случаях речь идет об обмене контентом между заданиями. На самом деле они принципиально отличаются:
- Если текущее задание не зависит от предыдущего, то есть может выполняться самостоятельно, но в присутствии контента работа будет идти быстрее, используйте кэш.
- Если текущее задание действительно зависит от результатов предыдущего, то есть не может выполняться само по себе, используйте артефакты и зависимости.
Помните: кэш ускоряет работу, но его может не быть, так что не полагайтесь на него. Эта статья о кэше.
Простая модель кэширования
Возьмем простое представление конвейера Gitlab CI и забудем, что задания могут выполняться на любых раннерах и любых хостах. Так проще разобраться.
Допустим, у нас один проект, два раннера Docker и три ветви.
Локальный кэш: том Docker
Если хотите установить общий локальный кэш для всех заданий на одном и том же раннере, задайте инструкцию cache в файле .gitlab-ci.yml.
default:
cache:
path:
- relative/path/to/folder/*.ext
- relative/path/to/another_folder/
- relative/path/to/file
Можно привязать кэш к конкретной ветви, установив предопределенную переменную «CI_COMMIT_REF_NAME» в качестве кэш-ключа (cache key).
default:
cache:
key: $CI_COMMIT_REF_NAME
path:
- relative/path/to/folder/*.ext
- relative/path/to/another_folder/
- relative/path/to/file
Предопределенная переменная «CI_JOB_NAME» в качестве кэш-ключа привязывает кэш к определенному заданию.
Локальный кэш: монтирование связей (технология Bind Mount)
Если том Docker не планируется использовать для кэширования, то при регистрации раннера установите опцию «монтирования связей» (bind mount). В этом случае уже не нужно задавать инструкцию cache в файле .gitlab-ci.yml.
#!/bin/bash
gitlab-runner register
--name="Bind-Mount Runner"
--docker-volumes="/host/path:/container/path:rw"
...
Фактически эта настройка позволяет заданиям на одном хосте совместно использовать кэш, не требуя установки распределенного кэша, о котором мы поговорим позже.
#!/bin/bash
gitlab-runner register
--name="Bind-Mount Runner"
--docker-volumes="/host/path:/container/path:rw"
...
gitlab-runner register
--name="Bind-Mount Runner Y"
--docker-volumes="/host/path:/container/alt/path:rw"
...
Распределенный кэш
Чтобы использовать общий кэш между всеми заданиями на нескольких раннерах и хостах, создайте раздел [runner.cache] в файле конфигурации config.toml.
[[runners]]
name = "Distributed-Cache Runner"
...
[runners.cache]
Type = "s3"
Path = "bucket/path/prefix"
Shared = true
[runners.cache.s3]
ServerAddress = "s3.amazonaws.com"
AccessKey = "<changeme>"
SecretKey = "<changeme>"
BucketName = "foobar"
BucketLocation = "us-east-1"
Предопределенная переменная «CI_COMMIT_REF_NAME» в качестве кэш-ключа привязывает кэш к определенной ветви между несколькими раннерами и хостами.
Использование в реальном мире
Мы рассмотрели упрощенную модель, в которой заранее известно, на каком раннере/хосте выполняется задание. Это позволяет понять концепцию, а иногда даже использовать ее в реальной жизни в таком виде, например, регистрировать локальные раннеры, выбирать тегами нужные и настраивать их.
В реальной жизни из-за автомасштабирования и ряда других причин мы можем не знать, где конкретно выполняется задание, но эта статья представляет собой, скорее, краткое резюме, а не справочное руководство. Вышеизложенного должно быть достаточно для понимания основ, чтобы перейти к более продвинутым настройкам.
Для развлечения вот вам небольшое упражнение.
Необходимо установить кэш для всех заданий конкретного этапа, которые выполняются на любом раннере и на любых хостах, но только в одинаковых ветвях:
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.
Cache
- 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.
- By default, protected and non-protected branches do not share the cache. However, you can change this behavior.
Artifacts
- 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:
-
Tag your runners and use the tag on jobs
that share the cache. - Use runners that are only available to a particular project.
-
Use a
key
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 a single runner for all your jobs.
- Use multiple runners that have
distributed caching,
where the cache is stored in S3 buckets. Shared runners on GitLab.com behave this way. These runners can be in autoscale mode,
but they don’t have to be. - Use multiple runners with the same architecture and have these runners
share a common network-mounted directory to store the cache. This directory should use NFS or something similar.
These runners must be in autoscale mode.
Use multiple caches
- Introduced in GitLab 13.10.
- Feature Flag removed, in GitLab 13.12.
You can have a maximum of four caches:
test-job:
stage: build
cache:
- key:
files:
- Gemfile.lock
paths:
- vendor/ruby
- key:
files:
- yarn.lock
paths:
- .yarn-cache/
script:
- bundle install --path=vendor
- yarn install --cache-folder .yarn-cache
- echo Run tests...
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
Introduced in GitLab Runner 13.4.
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:
variables:
CACHE_FALLBACK_KEY: fallback-key
job1:
script:
- echo
cache:
key: "$CI_COMMIT_REF_SLUG"
paths:
- binaries/
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:
cache: &global_cache
key: $CI_COMMIT_REF_SLUG
paths:
- node_modules/
- public/
- vendor/
policy: pull-push
job:
cache:
# inherit all global cache settings
<<: *global_cache
# override the policy
policy: pull
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.
For examples, see the GitLab CI/CD templates.
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
:
cache:
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:
cache:
key: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
To enable per-stage and per-branch caching:
cache:
key: "$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG"
Share caches across jobs in different branches
To share a cache across all branches and all jobs, use the same key for everything:
cache:
key: one-key-to-rule-them-all
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:
#
# https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/Nodejs.gitlab-ci.yml
#
image: node:latest
# Cache modules in between jobs
cache:
key: $CI_COMMIT_REF_SLUG
paths:
- .npm/
before_script:
- npm ci --cache .npm --prefer-offline
test_async:
script:
- node ./specs/start.js ./specs/async.spec.js
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.
# Cache modules using lock file
cache:
key:
files:
- package-lock.json
paths:
- .npm/
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:
job:
script:
- echo 'yarn-offline-mirror ".yarn-cache/"' >> .yarnrc
- echo 'yarn-offline-mirror-pruning true' >> .yarnrc
- yarn install --frozen-lockfile --no-progress
cache:
key:
files:
- yarn.lock
paths:
- .yarn-cache/
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:
#
# https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/PHP.gitlab-ci.yml
#
image: php:7.2
# Cache libraries in between jobs
cache:
key: $CI_COMMIT_REF_SLUG
paths:
- vendor/
before_script:
# Install and run Composer
- curl --show-error --silent "https://getcomposer.org/installer" | php
- php composer.phar install
test:
script:
- vendor/bin/phpunit --configuration phpunit.xml --coverage-text --colors=never
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:
#
# https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/Python.gitlab-ci.yml
#
image: python:latest
# Change pip's cache directory to be inside the project directory since we can
# only cache local items.
variables:
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
# Pip's cache doesn't store the python packages
# https://pip.pypa.io/en/stable/reference/pip_install/#caching
#
# If you want to also cache the installed packages, you have to install
# them in a virtualenv and cache it as well.
cache:
paths:
- .cache/pip
- venv/
before_script:
- python -V # Print out python version for debugging
- pip install virtualenv
- virtualenv venv
- source venv/bin/activate
test:
script:
- python setup.py test
- pip install flake8
- flake8 .
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:
#
# https://gitlab.com/gitlab-org/gitlab/-/tree/master/lib/gitlab/ci/templates/Ruby.gitlab-ci.yml
#
image: ruby:2.6
# Cache gems in between builds
cache:
key: $CI_COMMIT_REF_SLUG
paths:
- vendor/ruby
before_script:
- ruby -v # Print out ruby version for debugging
- bundle install -j $(nproc) --path vendor/ruby # Install dependencies into ./vendor/ruby
rspec:
script:
- rspec spec
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:
key:
files:
- Gemfile.lock
prefix: $CI_JOB_NAME
paths:
- vendor/ruby
test_job:
stage: test
before_script:
- bundle install --without production --path vendor/ruby
script:
- bundle exec rspec
deploy_job:
stage: production
before_script:
- bundle install --without test --path vendor/ruby
script:
- bundle exec deploy
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 ${GOPATH}/pkg/mod/
and
are cached for all of the go
projects:
.go-cache:
variables:
GOPATH: $CI_PROJECT_DIR/.go
before_script:
- mkdir -p .go
cache:
paths:
- .go/pkg/mod/
test:
image: golang:1.13
extends: .go-cache
script:
- go test ./... -v -short
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/<user>/<project>/<cache-key>/cache.zip . |
Docker | Locally, under Docker volumes: /var/lib/docker/volumes/<volume-id>/_data/<user>/<project>/<cache-key>/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
Introduced in GitLab 15.0.
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 |
Use the same cache for all branches
Introduced in GitLab 15.0.
If you do not want to use cache key names,
you can have all branches (protected and unprotected) use the same cache.
The cache separation with cache key names is a security feature
and should only be disabled in an environment where all users with Developer role are highly trusted.
To use the same cache for all branches:
- On the top bar, select Menu > Projects and find your project.
- On the left sidebar, select Settings > CI/CD.
- Expand General pipelines.
- Clear the Use separate caches for protected branches checkbox.
- Select Save changes.
How archiving and extracting works
This example shows two jobs in two consecutive stages:
stages:
- build
- test
before_script:
- echo "Hello"
job A:
stage: build
script:
- mkdir vendor/
- echo "build" > vendor/hello.txt
cache:
key: build-cache
paths:
- vendor/
after_script:
- echo "World"
job B:
stage: test
script:
- cat vendor/hello.txt
cache:
key: build-cache
paths:
- vendor/
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 thevendor/
directory is zipped intocache.zip
.
This file is then saved in the directory based on the
runner’s setting and thecache: 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 ofjob A
overwrites
things in the archive ofjob 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-<index>
, and the index increments by one. The old cache is not deleted. You can manually delete these files from the runner storage.
Troubleshooting
Cache mismatch
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:
stages:
- build
- test
job A:
stage: build
script: make build
cache:
key: same-key
paths:
- public/
job B:
stage: test
script: make test
cache:
key: same-key
paths:
- vendor/
-
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 ofjob 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):
stages:
- build
- test
job A:
stage: build
script: build
cache:
key: keyA
paths:
- vendor/
job B:
stage: test
script: test
cache:
key: keyB
paths:
- vendor/
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.