Skip to content
ImagineWorld

Using Geo to Create Distributed Read-Only Copies of GitLab

node_idnode-book_mastering-gitlab-12_chapter-22-using-geo-to-create-distributed-read-only-copies-of-gitlab
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num22
chapter_titleUsing Geo to Create Distributed Read-Only Copies of GitLab
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 22 — Using Geo to Create Distributed Read-Only Copies of GitLab

Section titled “Chapter 22 — Using Geo to Create Distributed Read-Only Copies of GitLab”

In the previous chapters, we created a basic scalable GitLab architecture using Terraform and Ansible. In this chapter, we will continue with this technique, but we scale down the number of nodes that we’ll use so that we don’t over complicate matters. To create globally synchronized read-only copies of GitLab instances, we will need to create Geo-enabled GitLab instances that can replicate data. The Geo feature is part of the GitLab enterprise license, so you’ll need this license or a trial version to activate it.

You could try and sync copies of databases and files yourself with standard tools such as rsync, but Geo is much more fine-grained than they are. It offers synchronization that’s based on events and doesn’t continually scan for change delta’s such as rsync. Another of Geo’s features is that it can do HA failover from your primary GitLab instance to a secondary one. We will demonstrate how to set up a two-node Geo installation in this chapter.

In this chapter, we will cover the following topics:

  • The basic architecture of this solution
  • Preparing the infrastructure
  • Setting up Geo

To successfully run the code sample you need a trail license from GitLab which you can generate here: https://about.gitlab.com/free-trial/. The license that you receive via email should be saved in the local copy of the code example repository in Chapter22/geo-setup/deploy/files directory in Gitlab.gitlab-license file.

To manage omnibus installations, you need to use a central configuration file called gitlab.rb. You’ll need to create it yourself or copy an example of one. A template of this configuration file is available at https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/files/gitlab-config-template/gitlab.rb.template. Please note that it isn’t updated after upgrades. In some sections of this chapter, I will quote and discuss parts of this file.

In order to create our virtual infrastructure, we are going to use Terraform (v0.11.12 or later). You can download it from https://www.terraform.io. Terraform is a multiplatform binary. This means it can run on Linux, macOS, and Windows. This makes it easy to install.

Terraform providers need the following:

  • provider.ansible v0.0.4: You can get it from https://github.com/nbering/terraform-inventory
  • provider.aws v2.1.0: Automatically downloaded with the terraform init command (see Starting with the code of Chapter 19, Creating a Basic HA Architecture Using Horizontal Scaling)
  • provider.tls v1.2.0: Automatically downloaded with the terraform init command(see Starting with the code of Chapter 19, Creating a Basic HA Architecture Using Horizontal Scaling)

To automate our deployments, we will use Ansible (version 2.7 or later). You can download it from https://github.com/ansible/ansible, or use a package manager such as brew or pip to install it.

To follow along with the instructions in this chapter, please download this book’s GitHub repository, along with its examples, which are available at https://github.com/PacktPublishing/Mastering-GitLab-12/tree/master/Chapter22.

The following diagram shows the architecture for this solution. The main feature of this setup is that you have a master GitLab installation on site A (called gitlab-eu ) and have it completely replicated to site B(called gitlab-us). This way, you can create read-only mirrors of a GitLab instance all over the world. Remote users can then fetch files and projects from that server and push them to the primary GitLab instance. To create instances in different AWS regions, we will need to create two Virtual Private Clouds(VPC) and copy the infrastructure. We need to make sure that the sites can reach each other:

What this boils down to is that we have to set up database replication and application replication, which is exactly what Geo does. It takes care of the management side of things. For this example, we chose site A to be Amazon’s Europe-Central-1 region and site B to be the US-West-1 region.

If we want to automate the installation of the GitLab Geo-enabled instances, we have to change our Terraform setup a bit. Because we want to use two different regions, we are going to use Terraform modules. In the previous chapters, we only used the context of the root module, but now we are going to expand on the module concept.

The Terraform AWS provider always operates in a certain region’s context, and we can use these modules to create a GitLab instance template that will be installed as service modules for site A and site B.

The example project has the following file structure:

.
├── connect.sh
├── deploy
│ ├── configure_replication.yml
│ ├── files
│ │ └── Gitlab.gitlab-license
│ ├── install_bastionhost.yml
│ ├── install_gitlab.yml
│ └── templates
│ ├── gitlab.rb.j2
│ ├── gitlab.rb.primary.j2
│ └── gitlab.rb.secondary.j2
├── main.tf
├── modules
│ └── services
│ ├── gitlab
│ │ ├── main.tf
│ │ ├── outputs.tf
│ │ └── vars.tf
│ └── keypair
│ ├── main.tf
│ ├── outputs.tf
│ └── vars.tf
├── readme.md
└── vars.tf

In the main directory, we have the following files:

  • connect.sh: A script so that we can SSH to the machines that are created
  • main.tf: The top-level Terraform declarations
  • readme.md: Provides an explanation about the files
  • vars.tf: Provides a definition of some of the variables that are used in other files

Now, let’s go through the files in this directory.

At the top of the file, you will see the different sites that are defined, all of which call the GitLab module in the modules/services/ directory.

The first site is the main site that’s located in the EU. The GitLab module takes several arguments that allow us to specify different settings for each site:

module "gitlab_eu" {
source = "modules/services/gitlab/"
region = "eu-central-1"
instance_type = "t2.medium"
vpc_cidr_block = "10.0.0.0/16"
subnet_frontend_cidr_block = "10.0.1.0/24"
}

The secondary Geo site is going to be in the US, on the West Coast. We also chose a different internal subnet to make it different from the EU one:

module "gitlab_us" {
source = "modules/services/gitlab/"
region = "us-west-2"
instance_type = "t2.medium"
vpc_cidr_block = "172.16.0.0/16"
subnet_frontend_cidr_block = "172.16.1.0/24"
}

The following entries in this file are the ansible_host definitions. We need them to be on this level because Ansible is going to execute transactions in all the regions. Because the declarations are on the top level, we can reference output variables in child modules. Another approach would be to run Ansible scripts separately for each location, but that would lead to a lot of duplication:

resource "ansible_host" "GITLABHOST001" {
inventory_hostname = "${module.gitlab_eu.gitlabhost_fqdn}"
groups = ["gitlab"]
vars
{
role = "primary"
geo_primary_address = "${module.gitlab_eu.lb_address}"
geo_secondary_address = "${module.gitlab_us.lb_address}"
ansible_user = "${var.sshuser}"
ansible_ssh_private_key_file = "${var.ssh_private_key_primary}"
ansible_python_interpreter = "${var.python_interpreter}"
ansible_ssh_common_args = " -o ProxyCommand=\"ssh -o StrictHostKeyChecking=no -i /tmp/mykey1.pem -W %h:%p -q ubuntu@${module.gitlab_eu.bastionhost_fqdn}\""
proxy = "${module.gitlab_eu.bastionhost_private_ip}"
subnet = "10.0.1.0/24"
}
}

The ansible_host declaration in the preceding code isn’t very different from what was shown in the previous chapters, but there are some differences. The first obvious one is that we define geo_primary_address and geo_secondary_address. These are the external addresses of the load balancers. We need these variables because Ansible will insert the values in the configuration files that are installed on each site. Another general difference is that you will see that more variables have been defined. This is happening because we have more sites now, and so some values have to be more generic.

This module is responsible for creating a public/private keypair that is used to connect to the instances with SSH. It was available in the previous chapters, but it was in the root module. Now, it is a standalone module that’s called from the GitLab module with certain arguments:

provider "aws" {
region = "${var.region}"
}
resource "tls_private_key" "mykey"
{
algorithm = "RSA"
rsa_bits = 4096
}
resource "aws_key_pair" "keypair"
{
public_key = "${tls_private_key.mykey.public_key_openssh}"
}

At the top of the preceding code, you can see the region that’s been defined. This is an argument on the top level that’s passed through to the child module.

The vars.tf file determines which variables are expected to be defined for this module:

variable region{}

As you can see, it should be called with the region argument.

The only function of this module is to create keys, so the output variable that’s defined is the value of this key:

output "mykey" {
value = "${aws_key_pair.keypair.key_name}"
sensitive = true
}

Usually, a generated key is sensitive information, and you can suppress the output of the value to the Terminal with sensitive=true. It’s false by default.

This module can be used as a template for GitLab installations. Compared to the structure of the .tf files in previous chapters, there are more variables being defined and less have been hardcoded. This is because using modules forces you to refactor quite a bit.

This is the main file of the GitLab module. It’s quite big, but we kept it this way to focus on the overall architecture. With Terraform, we could refactor this into a well-formed module structure, but we’ll keep it simple for this demonstration.

At the top of the file, we define the region so that we can use this variable in other modules:

provider "aws" {
region = "${var.region}"
}

The next module that we call is the keypair module, which will provider SSH key pairs to the instances. As you can see, the only arguments are the location of the module file and the region:

module "keypair" {
source = "../keypair"
region = "${var.region}"
}

Then, we define the actual EC2 instances. We use the output variable from the keypair module by referring to module.keypair.key_name. So, in order to call variables that exist in the child modules, you need to prepend module:

resource "aws_instance" "gitlab_host" {
ami = "${lookup(var.aws_ubuntu_amis,var.region)}"
subnet_id = "${aws_subnet.subnet_public_frontend.id}"
key_name = "${module.keypair.key_name}"
vpc_security_group_ids = ["${aws_security_group.sg_gitlab.id}"]
instance_type = "${var.instance_type}"
}

We also need to create a bastion host, which we will use to execute Ansible commands:

resource "aws_instance" "bastion_host" {
ami = "${lookup(var.aws_ubuntu_amis,var.region)}"
subnet_id = "${aws_subnet.subnet_public_frontend.id}"
key_name = "${module.keypair.key_name}"
vpc_security_group_ids = ["${aws_security_group.sg_bastionhost.id}"]
instance_type = "t2.micro"
}

Then, there is the very important load balancer node, which is the frontend component facing the internet:

resource "aws_elb" "lb" {
subnets = ["${aws_subnet.subnet_public_frontend.id}"]
health_check {
healthy_threshold = 2
unhealthy_threshold = 2
timeout = 3
target = "TCP:80"
interval = 30
}
listener {
instance_port = 80
instance_protocol = "http"
lb_port = 80
lb_protocol = "http"
}
listener {
instance_port = 5432
instance_protocol = "tcp"
lb_port = 5432
lb_protocol = "tcp"
}

As you can see, an additional port has been defined for PostgreSQL (5432), which is closed by default. We will add the firewall rule to allow traffic between the sites later. The rest of the objects that are defined in this file are the same as in the previous chapters.

In this file, a lot of the variables are defined for the GitLab module. All of them can be overridden, but have a default value set. The first variable is expected as an argument and it defines the region. This makes this module usable in multiple AWS regions:

variable "region" {
description = "Which Amazon region this instance will run"
}

Another input for this module is the type of Amazon instance we are using:

variable "instance_type" {
description = "Which type of Amazon EC2 instance to use"
}

For each region, we define the base image to be used:

variable "aws_ubuntu_amis"
{
description = "List of default AMI images per region"
default = {
"eu-central-1" = "ami-0f041b9708f60ca57"
"us-west-2" = "ami-0ddba1929e996e2dc"
}

We then define the management IPs (mgmt_ips) of hosts that can connect to the bastion hosts:

}
variable "mgmt_ips" {
default = ["0.0.0.0/0"]
}

The private range to be used in the VPC is also taken as input:

variable "vpc_cidr_block" {
description = "Which network range to use"
}

Just like the range, we need to use the frontend private network:

variable "subnet_frontend_cidr_block" {
description = "Which network range to use"
}

All of the variables in this file are used, and the ones without a default value should be given as input.

The GitLab module itself also has outputs that are defined. These are used in the ansible_host declarations in the top-level main.tf file.

The load balancer Fully Qualified Domain Name (FQDN)is as follows:

output "lb_address"{
value ="${aws_elb.lb.dns_name}"
}

The bastion FQDN is as follows:

output "bastionhost_fqdn" {
value= "${aws_instance.bastion_host.public_dns}"
}

The private IP of the bastion host is as follows:

output "bastionhost_private_ip" {
value= "${aws_instance.bastion_host.private_ip}"
}

The private IP of the GitLab instance is as follows:

output "gitlab" {
value= "${aws_instance.bastion_host.private_ip}"
}

The FQDN of the GitLab instance is as follows:

output "gitlabhost_fqdn" {
value = "${aws_instance.gitlab_host.public_dns}"
}

The three files (main.tf, vars.tf, and outputs.tf), when put together, form the GitLab module that’s called for each site.

GitLab Geo is a feature of GitLab that is part of the premium Enterprise version and higher. It is used to create a replica of a whole GitLab instance in another geographical location. Items such as user accounts, issues, events, and other objects are synced—not only items from the database, but also files from the filesystem.

There are several steps involved in installing Geo for your environment:

  1. Install the GitLab software and license on both nodes, but don’t activate them.
  2. Prepare the database replicas.
  3. Change the SSH key lookup method to the database.
  4. Add the secondary node via the web UI.

The first two steps in our example project can be executed by the Ansible scripts that are part of the repository for this book. Steps 3 and step 4 have to be done manually. Let’s deep dive into these steps.

The Ansible playbook that is used to configure the node consists of different parts. It consists of the following:

  • Script: install_gitlab_primary.yml
  • Template: gitlab.rb.j2
  • Run command: ansible-playbook -i /usr/local/bin/terraform.py deploy/install_gitlab_primary.yml

This Ansible script will configure and start the database replication between the primary and secondary Geo nodes.

The only entry in the gitlab.rb file is geo_primary_role. Assigning this role will install every component on the server:

roles ['geo_primary_role']

We do this in order to install the license automatically as well. It should be placed in the files directory of this repository before running the Ansible script. It will copy the file to /etc/gitlab.

The following part of the Ansible script is responsible for doing this:

- name: Install license file to enable geo functionality
copy:
src: "Gitlab.gitlab-license"
dest: /etc/gitlab
mode: 0755

It will only work on the initial installation of GitLab. Afterward, changes to the license have to be done via the web UI. Also, if you don’t have this license file in place, the installation will fail. Comment out or remove the task if you want to install the license later or via the web UI.

When GitLab is installed, we can run the scripts so that we can start replicating the databases.

The Ansible playbook that is used to configure the node consists of different parts. It consists of the following:

  • Script: configure_replication.yml
  • Template: gitlab.rb.primary.j2, gitlab.rb.secondary.j2
  • Run command: ansible-playbook -i /usr/local/bin/terraform.py deploy/configure_replication.yml

This Ansible script will configure and start the database replication between the primary and secondary Geo nodes.

We have to define the main URL for the GitLab instance:

external_url 'http://{{ hostvars[groups['gitlab'][0]]['geo_primary_address'] }}'

For this demonstration, we will disable SSL:

letsencrypt['enable'] = false

The role remains the same:

roles ['geo_primary_role']

In the Ansible script, we are going to generate a database password that we will use on our secondary node as well:

postgresql['sql_user_password'] = "{{ generated_db_pass }}"

We will explicitly make the PostgreSQL database listen on the eth0 interface:

postgresql['listen_address'] = "{{ hostvars[groups['gitlab'][0]]['ansible_eth0']['ipv4']['address'] }}"

Here, we will define the IP addresses that will be allowed to connect to the database. We have put the primary and secondary hostnames in here by using variables from the Ansible inventory:

postgresql['md5_auth_cidr_addresses'] = %w({{ hostvars[groups['gitlab'][0]]['geo_primary_address'] }} {{ hostvars[groups['gitlab'][0]]['geo_secondary_address'] }})

The following setting determines that there is only one other node that is being replicated. If we are going to add more Geo nodes, we have to increase this number:

postgresql['max_replication_slots'] = 1

In the Ansible script, we create a special replication user that is used to synchronize the databases:

postgresql['sql_replication_user'] = "gitlab_replication"

For the first installation of this synchronization, we don’t want migrations to run, nor change the database structures:

gitlab_rails['auto_migrate'] = false

After running the first part of the Ansible script, you should see a PostgreSQL database ready for synchronization and a TLS (Transport Layer Security) certificate ready for distribution in the project directory (it is copied by the script).

The secondary database node is also configured in this script. The gitlab.rb file is a bit different, but we can see the role that’s defined at the top:

roles ['geo_secondary_role']

Here’s listen_address for PostgreSQL that’s defined:

postgresql['listen_address'] = ""{{ hostvars[groups['gitlab'][1]]['ansible_eth0']['ipv4']['address'] }}""

We can also see the two addresses of the database servers in the array of allowed hosts:

postgresql['md5_auth_cidr_addresses'] = ["{{ hostvars[groups['gitlab'][1]]['ansible_eth0']['ipv4']['address'] }}"]

The database password hash that was generated on the primary node is inserted here, as well as the clear text password:

postgresql['sql_user_password'] = "{{ generated_db_pass }}"
gitlab_rails['db_password'] = 'packtpub'

The Geo tracking database is also installed on the secondary node. This can help speed up synchronization:

geo_secondary['db_fdw'] = true

After running this Ansible script, the databases should be syncing. The next step is to prepare GitLab itself.

The Ansible script that’s used to install GitLab already copies the host keys and settings in order to enable fast SSH key lookup. The only thing that’s left to do to enable this feature (which is necessary for Geo) is to disable writes to the authorized_keys file by using GitLab. The following screenshot shows how to adjust performance optimization:

This is done by unchecking the Write to “authorized_keys” file option in Admin Area | Settings | Network | Performance optimization in the web UI.

Visit the admin page for Geo by going to Admin Area | Geo (/admin/geo/nodes). Then, you have to do the following:

  1. Add the secondary Geo by specifying the HTTP(s) URL.
  2. Make sure that This is a primary node isn’t checked.
  3. If you want, you can pick which groups should be copied by the secondary node.
  4. Don’t fill in anything to replicate.
  5. Click the Add button.
  6. On your secondary server, restart the service:
gitlab-ctl restart
  1. You can run a check to see whether everything is in order:
gitlab-rake gitlab:geo:check
  1. Go to the primary server and execute the check:
gitlab-rake gitlab:geo:check

If everything is OK, the initial synchronization will start in the background.

Since GitLab 12.0, hashed storage has become mandatory for using Geo. It was introduced in GitLab 10.0 and is much faster then the legacy storage option. The biggest use case for using hashed storage is that it eliminates the synchronization of URL and disk location(foldername). Before hashed storage, when a project was moved to another group, it was effectively relocated to another top-level folder. If, for any reason, a backup has to be restored, you had to hope that the name wasn’t already taken. With hashed storage, every project uses a unique ID.

For Geo, this means that a move to another top-level folder will not trigger mass synchronizations. It only has to change a reference. This makes using hashed storage with Geo a lot faster as well.

You can enable this by going to the Repository page in the Admin Area | Settings | Repository settings and checking the Use hashed storage paths for newly created and renamed projects checkbox:

Now, let’s create a new project and check the file structure of the disk of one of the nodes in the /var/opt/gitlab/git-data/repositories path:

$tree -L 4 "@hashed"/
@hashed/
└── e6
└── 29
├── e629fa6598d732768f7c726b4b621285f9c3b85303900aa912017db7617d8bdb.git
│ ├── HEAD
│ ├── branches
│ ├── config
│ ├── description
│ ├── hooks
│ ├── info
│ ├── objects
│ └── refs

You should see that there are no project names anymore, just hash values.

At this point, the secondary Geo should be set up. We can check the status of the node by browsing to Admin Area | Geo. You should see an enabled Geo secondary node and some information about the state of the synchronization. When the first synchronization starts, the initial sync called ‘backfill’ runs:

If you encounter errors in this dashboard, then note that they are mainly caused by the database replication not working properly or because something is blocking communication between the nodes. Firewalls could be blocking traffic, or network links may be down. It is also possible that your custom SSL certificates aren’t properly installed or are not valid.

Currently, this is what is synced:

  • Git repositories
  • Wikis
  • Large File storage (LFS)objects
  • Issues, merge requests, snippets, and comment attachments
  • Users, groups, and project avatars

In this section, we have covered setting up Geo with some Ansible scripts that did a lot of the manual work in the Terminal. We finished by setting up some options in the web UI.

In this chapter, we created a final HA architecture of GitLab. If you want to globally sync GitLab to different locations, you can use the Geo feature, which is part of the Enterprise Edition of GitLab. You can set up two VPCs in Amazon and create two separate hosts that will synchronize.

  1. How many load balancers are there in this chapter’s scenario?
  2. Which Terraform feature is used in this chapter?
  3. Where can you upload a license to install on the command line?
  4. What is necessary to run Geo and make it work?
  5. How is the initial synchronization called?
  • Mastering Ansible – Third Edition by James Freeman and Jesse Keating:
  • Getting Started with Terraform – Second Edition by Kirill Shirinkin:
  • AWS Certified Developer – Associate Guide – Second Edition by Vipul Tankariya and Bhavin Parmar:
  • Learn Linux Shell Scripting – Fundamentals of Bash 4.4 by Sebastiaan Tammer: