Skip to content
ImagineWorld

Autoscaling GitLab CI Runners

node_idnode-book_mastering-gitlab-12_chapter-17-autoscaling-gitlab-ci-runners
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num17
chapter_titleAutoscaling GitLab CI Runners
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 17 — Autoscaling GitLab CI Runners

Section titled “Chapter 17 — Autoscaling GitLab CI Runners”

In the previous chapter, we were able to scale GitLab Runners using the Kubernetes executor. Depending on your requirements of how many jobs should be able to run concurrently, the number of available Runners in a Kubernetes cluster can go up or down. Having a big number of runners available can be very costly. Even if they were to be turned off, they would still cost money. It’s much better to have them created on demand and destroyed when they are no longer needed.

There is another GitLab Runner executor that can behave in this elastic way and dynamically add or remove Runner instances, and this is known as the Docker Machine executor. We will show you what this looks like from an architectural point of view, explain some of its settings, and provide you with some examples of running the Docker Machine executor with the VirtualBox driver and the Amazon EC2 driver.

In this chapter, we will cover the following topics:

  • Runner client architecture
  • Setting up the environment
  • Configuring the GitLab Runner

You can find the code file for this chapter in this book’s GitHub repository at https://github.com/PacktPublishing/Mastering-GitLab-12/tree/master/Chapter17.

The other requirements for this chapter are as follows:

First, we will describe the architecture of this solution. Expanding on the architecture that was put forward in previous chapters, we have a GitLab instance with a GitLab CI that receives a request from a GitLab Runner that’s running a dedicated host. This can be either a local virtual machine or an instance in the cloud. The Runner is equipped with the Docker Machine program.

The Docker Machine executor type is basically a GitLab Runner that executes Docker Machine commands. With Docker Machine, you can create virtual hosts that run the Docker Engine. You can control these hosts with it and create new virtual machines with Docker Engine installed, which in turn can run GitLab Runner container instances. This is explained in the following diagram:

In the preceding diagram, you can see the Docker Machine component and that it can instantiate multiple runners. There are also two other components in the diagram called a Caching server (which can store dependencies for builds) and the Docker registry proxy (which can cache Docker images from places such as the Docker Hub). Both components will be explained in more detail in the Configuring the Runner section.

To enable a Docker Machine-based Runner, the following steps have to be performed:

  1. Prepare a bastion host as the host where Docker will create new machines.
  2. Deploy the GitLab Runner software on this machine.
  3. Install Docker Machine.

For this example, we chose my macOS-based machine. This can be a Linux virtual machine or your laptop—any machine that can run a recent version of the GitLab Runner software. The only function this host will have is executing the GitLab Runner software with the Docker Machine executor. It should be tightly secured as a bastion to withstand attacks since it can control multiple Runner instances through the docker-machine commands, and that makes it a target.

On macOS, we use the Homebrew package manager. To install the Runner software, you can execute the following command:

brew install gitlab-runner

After that, you can register the Runner, as shown in Chapter 15, Installing and Configuring GitLab Runners:

gitlab-runner register

Choose the Docker Machine executor when you’re asked for an executor in the registration process.

After the Runner has been registered, don’t start it just yet—we need to edit the config.toml configuration file that’s located in ~/.gitlab-runner/config.toml on macOS. We will do that in the Configuring the Runner section.

First, though, we need to install the Docker Machine binary before we configure the Runner in order to start the Docker Machine executor.

If you’ve installed Docker on macOS or on Windows, you will already have the binary installed. You can test the installation by using the following command:

$ docker-machine -v
docker-machine version 0.16.1, build cce350d7

You can create new Docker hosts with this tool. They can be created on your local machine or network, but also in the cloud with the help of big providers such as Microsoft, Amazon, and Google. Docker Machine has plugins for many systems. The following is a list of them:

  • All VMware products
  • Virtualbox
  • Microsoft Hyper-V
  • DigitalOcean
  • Amazon Web Services (EC2)
  • Microsoft Azure
  • Exoscale
  • Google Computing Engine
  • Scaleway
  • IBM Softlayer
  • Rackspace
  • OpenStack
  • Linode

If you are running Linux, you can download and install Docker Machine from https://github.com/docker/machine/releases/.

If you look at the Dockerfile of GitLab Runner on https://hub.docker.com/r/gitlab/gitlab-runner/dockerfile, which is used to build the default container, there is a line that says the following:

wget -q https://github.com/docker/machine/releases/download/v0.7.0/docker-machine-Linux-x86_64 -O /usr/bin/docker-machine && \
chmod +x /usr/bin/docker-machine

The Docker Machine binary is installed directly in this container image and is used by the GitLab Runner software. When you have verified that the Docker Machine binary is available, the next step is to configure the Runner.

Now that you’ve installed the Runner software and Docker Machine, it’s time to edit the Runner configuration file. On macOS, you can find the config.toml file in ~/.gitlab-runner/config.toml. It is in your home directory because the Runner runs in the user space on macOS.

Now, we will take a look at some of the configuration options you can specify in the config.toml file that are specifically for the autoscaling Runner.

Most organizations don’t have the need for 24/7 capacity since they don’t need to use CI runners all of the time. The most work is done during work hours in a regular work week, and at the weekends, there’s less of a need for software to be built. In this situation, it makes no sense to have machines sitting idle, waiting for jobs. By specifying a schedule with the OffPeakPeriods option, you can specify these times of lower productivity. During those times, the parameters to control the creation of the runner’s capacity are different. You specify them by putting OffPeak in front of it. Therefore, IdleCount becomes OffpeakIdleCount, IdleTime becomes OffPeakIdletime, and so on. The functionality of the algorithm stays the same.

In the following schedule (which is common), you can see off-peak times on weekdays during the night, evening, and the entire weekend:

[runners.machine]
OffPeakPeriods = [
"* * 0-9,18-23 * * mon-fri *",
"* * * * * sat,sun *"
]

GitLab Runners have a built-in caching mechanism. It can be set on a global level, as well as for an individual project.

You can set a path in your config.toml configuration file so that it will cache every job:

[runners.cache]
Path = "/node_modules"

You can set which path is to be cached in the .gitlab-ci.yml file for the project itself:

cache:
paths:
- node_modules/

The preceding settings apply to the context of just a single Runner host. If we use autoscaling, we need a way to have this cache shared by all of the runners to help gain speed. We can use external storage such as an S3 bucket to act as a cache. We just have to add the [runners.cache.s3] part to the config.toml file of the runners:

[runners.cache.s3]
ServerAddress = "s3-website-us-east-1.amazonaws.com"
BucketName = "joustie-gitlab-runner-cache"
AccessKey = "xxx"
SecretKey= "xxxx"
Insecure = false

If this is your first time doing this, it will try to get the cache.zip file from the S3 storage bucket. However, if there is no file, it will complain and continue:

Checking cache for default...
FATAL: file does not exist

After the build, which populates the node_modules directory with dependencies, the contents of that directory is zipped and sent to the S3 storage bucket:

Creating cache default...
node_modules/: found 5728 matching files
Uploading cache.zip to https://joustie-gitlab-runner-cache.s3.amazonaws.com/project/14/default
Created cache
Job succeeded

If we retry the job, we will find that there’s now a cache.zip file in S3, and it will be used instead of downloading all of those node dependencies again:

Checking cache for default...
Downloading cache.zip from https://joustie-gitlab-runner-cache.s3.amazonaws.com/project/14/default
Successfully extracted cache

Another situation that can slow down building considerably is that the runners continuously download Docker containers from the internet. It is a much better idea to create a proxy for that. In runners.machine, you can specify which engine-registry-mirror should be used. If this is used on your local network, this saves a lot of traffic. Here, you see the section as I used it in our example project:

MachineOptions = [
"engine-registry-mirror=http://192.168.1.10:6000"
]

In the most basic way, the Docker Machine executor uses docker-machine to spawn new instances of the GitLab Runner container.

You can combine this with other features, such as shared caching and using a dedicate container registry to facilitate large amounts of instances.

If you enable these settings for your runner, you need to deploy a caching server and a registry mirroring service, which we will show you in the next section.

The two extra machines are necessary to help with performance when your plan is to deploy an entire elastic fleet of GitLab Runners. If you have more than five runners that can operate simultaneously, you will already gain an advantage when running a registry proxy and a caching server. An extra feature you get is that a bit of high availability is introduced in your architecture: you are able to do builds when your internet connection is flaky or offline.

For a proxy container registry, you need to have a proxy that implements the Docker Registry HTTP API V2, which we will install in the next section.

There is a convenient Docker container readily available to fulfill this role. You can start this Docker container immediately by using the following code:

docker run -d -p 6000:5000 -e REGISTRY_PROXY_REMOTEURL=https://registry-1.docker.io --name runner-registry registry:2

If you create such a registry proxy and check the log file when the runners start a job, you will find that the proxy serves the Runner by fetching and caching images:

$ docker logs registry -f
172.17.0.1 - - [25/May/2019:14:28:40 +0000] "GET /v2/ HTTP/1.1" 200 2 "" "docker/18.09.6 go/go1.10.8 git-commit/481bc77 kernel/4.14.116-boot2docker os/linux arch/amd64 UpstreamClient(Go-http-client/1.1)"
...

There isn’t much to configure, but you can find more information here: https://hub.docker.com/_/registry.

There are two options for creating a caching server. You can either get an S3 bucket in Amazon or another cloud provider or run an object storage service yourself such as MinIO, which can be found at https://min.io.

Log in to the Amazon Web Services console and find the S3 dashboard via Services | S3. Click on Create bucket:

We have named it joustie-gitlab-runner-cache and left the rest as the default:

This is also conveniently available as a Docker image. It is recommended to run this on a dedicated host because the storage that’s involved can grow quite large, and you don’t want this service to take down any other service that is running on that host.

Run the container with the following command:

docker run -it -p 9005:9000 -v ~/.minio:/root/.minio -v /s3:/export --name caching-server minio/minio:latest server /export

Take note of the /s3 volume that is mounted in the container, which will serve as the directory that stores the cached objects.

The output of the preceding command will appear after some time:

latest: Pulling from minio/minio
e7c96db7181b: Already exists
94d4d681d0f2: Pull complete
664c3f016f88: Pull complete
b3235cce6961: Pull complete
Digest:sha256:244c711462a69303c0aa4f8d7943ba8b36dd55246e29da44c6653e39eaa42e70
Status: Downloaded newer image for minio/minio:latest

The container image will be downloaded.

After that, the MinIO container will start and report the location it uses, as well as AccesKey and SecretKey, which are to be used by the runners:

Endpoint: http://172.17.0.4:9000 http://127.0.0.1:9000
AccessKey: xxx
SecretKey: xxx

We will demonstrate the usage of the cache by building a Node.js example project. It contains a node_modules directory, which we specify as a cached location in the .gitlab-ci.yml file.

When you build the Node.js project using a GitLab Runner, it will report its use of the cache in the Runner job log file:

node_modules/: found 5728 matching files
Uploading cache.zip to http://192.168.178.82:9005/joustie-gitlab-runner-cache/project/14/default
Created cache
Job succeeded

When we looked on the dedicated machine where the MinIO container was running, we found the following directory structure when we typed in the tree command in /s3 (this is the directory that’s used by the MinIO Docker container to store objects):

$tree
.
└── joustie-gitlab-runner-cache
└── project
└── 14
└── default
3 directories, 1 file

We ran the GitLab Runner job again, which found cache.zip in the MinIO bucket.

This was an example of using a single runner. However, you may want to use these options to scale your Runner instances. Let’s look at this in the next section.

In the previous section, we configured the software and prepared our environment so that we could scale up and down the number of runners while also providing some shared services like a registry proxy and a caching server. Now, let’s look at two examples. We will run jobs on a Runner that’s been configured to use VirtualBox and one that’s been configured to use Amazon Web Services. VirtualBox is the open source virtualization solution from Oracle and can be found at https://www.virtualbox.org/.

Almost all of the Runner configuration files (the config.toml file) can be identical; we only change the machine driver part. Let’s start with the VirtualBox option.

We start with the local gitLab-runner service with the config file for VirtualBox:

brew services start gitlab-runner

After a few seconds, we will see that VirtualBox spins up a number of virtual machines:

When we started a build of the event manager project in Chapter 10, Create Your Product, Verify, and Package it, we saw that it needs more runners (five parallel jobs) to run the pipeline. Therefore, we will start more machines:

When the build has finished, after IdleTime has gone by, the number of machines will be reduced:

The VirtualBox driver is an excellent choice if you already have some servers with VirtualBox installed.

If you change the machine driver from VirtualBox to Amazon EC2 and restart the runners, Docker Machine will spin up runners in Amazon if you have your credentials saved in your home directory or inserted in your shell environment. If not, then you will need to save them in the config.toml file.

After some time, the runners will appear in the EC2 web interface:

When those runners are started, you can change your Docker context to the one in Amazon so that you can run Docker commands and control those machines:

eval $(docker-machine env runner-fatr91wm-elastic-runner-1558647049-87941946)

When you access the logs of the Runner on your bastion host, you will see that it will scale down the number of machines to IdleCount:

$docker logs runner-fatr91wm
gitlab-runner[69056]: WARNING: Removing machine : Too many idle machines

If we start the same job from earlier (event manager project), we will see that many jobs are queued following the start of the build pipeline:

The docker-machine ls command will show us that many EC2 instances are started on AWS by the autoscaling GitLab Runner:

$ docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS
runner-fatr91wm-elastic-runner-1558702358-7e149fd0 * amazonec2 Running tcp://3.86.53.66:2376 v18.09.6
runner-fatr91wm-elastic-runner-1558702588-f8114aa8 - amazonec2 Running tcp://34.207.177.20:2376
runner-fatr91wm-elastic-runner-1558702591-6e1b6fd9 - amazonec2 Running tcp://34.235.132.231:2376
runner-fatr91wm-elastic-runner-1558702594-dd75b49b - amazonec2 Running tcp://35.175.240.226:2376

You can also view new Runner instances in the AWS web console:

After successfully completing some of the jobs in the pipeline, the Runner will scale back down again:

As you can see, it’s quite simple to change the Docker Machine driver in the Runner configuration file and get the same behavior. The Runner scaled up virtual machines in VirtualBox are used to run Docker containers, as well as Amazon Web Services.

In this chapter, we explained the autoscaling feature of GitLab Runners. Like in Kubernetes, it gives you the option of creating Runner instances on demand and scaling back in times of less need. Under the hood, it uses Docker Machine to manage these replicas. There are several drivers available that instantly allow runners to be created on a big list of platforms.

In the next chapter, we will take a look at the options for monitoring all of these instances.

  1. What Docker feature is used by the docker-machine executor?
  2. What additional servers are recommended when you use autoscaling?
  3. In what file is the runner’s distributed cache saved?
  4. What is the name of the object storage that was used in this chapter?
  5. What is the name of the configuration file of a GitLab Runner?
  6. What is the name of the Docker image that’s used as a registry cache?
  • Getting Started with Containerization, by Gabriel N. Schenker, Hideto Saito, Hui-Chuan Chloe Lee, and Ke-Jou Carol Hsu:
  • Mastering Docker – Third Edition, by Russ McKendrick and Scott Gallagher:
  • Getting Started with Oracle VM VirtualBox, by Pradyumna Dash:
  • Hands-On AWS System Administration, by Glauber Gallego, Daniel Stori, and Satyajit Das: