gitlab omnibus что это

Создание, настройка и использование собственного Git-сервера

Материал, перевод которого мы сегодня публикуем, посвящён настройке Git-серверов. Git — это система управления версиями, разработанная Линусом Торвальдсом. Git пользуются миллионы людей во всём мире. Компании, вроде GitHub, предлагают службы хостинга кода, основанные на Git. По информации, которую можно найти в различных публикациях, GitHub является крупнейшим сервисом для хостинга IT-проектов. В частности, в 2017-м году сообщество GitHub достигло 24 миллионов разработчиков, которые трудятся над 67 миллионами репозиториев. В наши дни GitHub пользуются абсолютно все — от программистов-одиночек, до крупных организаций. Надо сказать, что даже компания Google перешла на GitHub, закрыв собственный проект схожей направленности.

Зачем нужен собственный Git-сервер?

В подобных ситуациях, для того, чтобы обойти ограничения, или если вам нужно контролировать то, что происходит с вашими репозиториями, лучше всего создать собственный Git-сервер. Это, с одной стороны, поможет сэкономить, а с другой — даст полный контроль над сервером. Среди продвинутых пользователей Linux весьма распространена практика использования собственных Git-серверов, размещаемых, можно сказать, бесплатно, на уже используемых ими серверах.

В этом руководстве мы поговорим о двух подходах к управлению кодовой базой с использованием собственного Git-сервера. Первый заключается в использовании обычного Git-сервера, а второй — в применении инструмента с графическим интерфейсом GitLab. В качестве платформы для экспериментов тут используется сервер на полностью пропатченной Ubuntu 14.04 LTS, развёрнутый на VPS.

Использование Git

Здесь мы рассматриваем сценарий, в соответствии с которым у нас имеется удалённый сервер и локальный сервер. Работаем мы периодически то с одним, то с другим.

Для начала установим Git на этих двух машинах. Git можно установить либо из пакета, доступного в репозитории используемого дистрибутива, либо вручную. Тут мы воспользуемся простейшим методом:

Затем добавим пользователя для Git:

Для того чтобы упростить доступ к удалённому серверу, настроим вход по ssh без пароля.

Создадим ssh-ключи на локальном компьютере:

Система спросит у вас о том, куда нужно сохранить ключ. Если вас устраивает стандартное место хранения ключа, просто нажмите Enter. Далее вам предложат задать пароль, который будет нужен для доступа к удалённому серверу.

Вышеописанная команда генерирует два ключа — открытый и закрытый. Запишите или запомните расположение открытого ключа. Он понадобится нам на следующем шаге.

Теперь надо скопировать эти ключи на сервер, что даст возможность наладить канал связи между двумя машинами. На локальном компьютере выполните следующую команду:

Теперь подключитесь по ssh к серверу и создайте директорию проекта для Git. Для репозитория можно использовать любую папку, которая покажется вам подходящей:

Затем перейдите в эту директорию:

Создайте пустой репозиторий:

Если команда успешно сработала, вы увидите сообщение, подобное следующему:

Теперь нужно создать Git-репозиторий на локальной машине. Для этого создаём директорию:

Далее, создаём в ней файлы проекта, и, оставаясь в ней, инициализируем репозиторий:

Об успешной инициализации репозитория можно судить по такому сообщению:

Теперь добавим файлы проекта в репозиторий:

До сих пор мы работали на локальном сервере. Теперь нам нужно отправить локальные данные на удалённый сервер, что сделает их доступными через интернет и позволит организовать совместную деятельность нескольких разработчиков:

Теперь можно отправлять изменения с локальной машины на сервер или загружать данные с сервера, используя, соответственно, опции push или pull :

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

В данной команде /home/swapnil/project.git — это путь к папке проекта на удалённом сервере, в вашем случае тут будет другой путь.

Затем, после клонирования, надо перейти в директорию проекта:

У вас, вместо project будет имя другой директории. Теперь можно приступать к работе над проектом, принимать изменения и отправлять их на сервер:

Мы полагаем, что вышеприведённых сведений достаточно для того, чтобы помочь тем, у кого не было опыта работы с Git, приступить к использованию собственного Git-сервера. Если вам нужен некий инструмент с графическим интерфейсом, позволяющий работать с проектом на локальной машине, можно воспользоваться чем-то вроде QGit или GitK для Linux.

QGit — графический инструмент для локальной работы с Git-репозиториями

Использование GitLab

Выше мы описали систему, позволяющую организовать совместную работу над проектами с помощью Git, полностью основанную на средствах командной строки. Работать в такой среде, конечно, сложнее, чем с GitHub. По иронии судьбы, хотя GitHub — это крупнейший в мире сервис для хостинга кода, его собственный код закрыт. Это — не опенсорсный проект, то есть, нельзя взять этот код и создать на его основе собственный GitHub. В отличие от чего-то вроде WordPress и Drupal, код GitHub нельзя загрузить и развернуть на собственном сервере.

Но, как это обычно бывает в мире опенсорса, проектам с закрытым кодом можно найти замену. В данном случае заменой GitHub может послужить весьма привлекательный опенсорсный проект GitLab. Он позволяет всем желающим разворачивать на собственных серверах нечто подобное GitHub. При этом GitLab можно использовать и для поддержки работы крупной компании или большой команды, и для организации собственного репозитория для небольшого проекта, который пока не готов к тому, чтобы представить его широкой общественности.

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

Свободно распространяемая версия GitLab имеет две редакции — бесплатную Community Edition (Core) и платную Enterprise Edition (существуют её варианты Starter, Premium и Ultimate). Последняя основана на Community Edition, которая отлично масштабируется, и, кроме того, включает в себя некоторые дополнительные возможности, ориентированные на организации. Это немного напоминает позиционирование WordPress.org и WordPress.com.

Среди возможностей GitLab можно отметить управление Git-репозиториями, средства обзора кода, наличие системы отслеживания ошибок, ленты активности, поддержку вики-страниц. Здесь имеется и GitLab CI — система непрерывной интеграции.

Многие VPS-провайдеры, вроде DigitalOcean, предлагают пользователям дроплеты GitLab. Если вы хотите развернуть GitLab на собственном сервере, вы можете установить эту систему вручную. GitLab предлагает пакет Omnibus для различных операционных систем. Прежде чем установить GitLab, может возникнуть необходимость в настройке почтового SMTP-сервера для того, чтобы система могла отправлять электронную почту. Рекомендовано для этих целей пользоваться Postfix. Поэтому, перед установкой GitLab, установим Postfix:

В процессе установки Postfix система задаст вам несколько вопросов. Не стоит пропускать ответы на них, но если ответы на них не даны, можно перенастроить систему, выполнив следующую команду:

После запуска этой команды нужно указать параметр Internet Site и задать почтовый идентификатор для домена, который будет использоваться GitLab. Далее, надо будет указать имя пользователя для Postfix и почтовый адрес. Значения остальных параметров можно не менять. После установки и настройки Postfix можно заняться GitLab.

Загрузим свежий пакет отсюда с помощью wget :

Теперь установим его:

Настроим и запустим GitLab:

Теперь надо будет настроить доменное имя в конфигурационном файле, что даст возможность работать с GitLab. Откроем файл:

Читайте также:  хонингование цилиндров что это надо ли делать

Сайт GitLab, открытый в браузере

Смена пароля на сайте GitLab

После того, как пароль изменён, можно войти на сайт и заняться работой с проектами.

Работа с проектами в GitLab

GitLab — это серьёзная система, имеющая массу возможностей. Как в них разобраться? Позволим себе привести тут несколько изменённую цитату из фильма «Матрица»: «Увы, невозможно рассказать о том, что умеет GitLab. Вы должны увидеть это сами».

Уважаемые читатели! Пользуетесь ли вы собственными Git-серверами? Если да — просим рассказать о том, как вы их настраиваете и поддерживаете.

Источник

Omnibus GitLab Architecture and Components

Omnibus GitLab is a customized fork of the Omnibus project from Chef, and it uses Chef components like cookbooks and recipes to perform the task of configuring GitLab in a user’s computer. Omnibus GitLab repository on GitLab.com hosts all the necessary components of Omnibus GitLab. These include parts of Omnibus that is required to build the package, like configurations and project metadata, and the Chef related components that will be used in a user’s computer after installation.

An in-depth video walkthrough of these components is available on YouTube.

Software Definitions

GitLab project definition file

A primary component of the omnibus architecture is a project definition file that lists the project details and dependency relations to external softwares and libraries.

Individual software definitions

Omnibus GitLab follows a batteries-included style of distribution. All of the software, libraries and binaries necessary for the proper functioning of a GitLab instance is provided as part of the package, in an embedded format.

Sometimes, a software’s source code may have to be patched to use it with GitLab. This may be to fix a security vulnerability, add some functionality needed for GitLab, or make it work with other component of GitLab. For this purpose, Omnibus GitLab consists of a patch directory, where patches for different software are stored.

For more extensive changes, it may be more convenient to track the required changes in a branch on the mirror. The pattern to follow for this is to create a branch from an upstream tag or sha making reference to that branchpoint in the name of the branch. As an example, from the omnibus codebase, gitlab-omnibus-v5.6.10 is based on the v5.6.10 tag of the upstream project. This allows for us to generate a comparison link like https://gitlab.com/gitlab-org/omnibus/compare/v5.6.10. gitlab-omnibus-v5.6.10 to identify what local changes are present.

Global GitLab configuration template

GitLab Cookbook

Omnibus GitLab, as previously described, uses many of the Chef components like cookbooks, attributes, and resources. GitLab EE uses a separate cookbook that extends from the one GitLab CE uses and adds the EE-only components. The major players in the Chef-related part of Omnibus GitLab are the following:

Default Attributes

Default attributes, as the name suggests, specifies the default values to different settings provided in the configuration file. These values act as fail-safe and get used if the user doesn’t provide a value to a setting, and thus ensure a working GitLab instance with minimum user tweaking being necessary.

Recipes

Definitions

Definitions can be considered as global-level macros that are available across recipes. Some common uses for definitions are defining the ports used for common services, and listing important directories that may be used by different recipes. They define resources that may be reused by different recipes.

Templates for configuration of components

As mentioned earlier, Omnibus GitLab provides a single configuration file to tweak all components of a GitLab instance. However, architectural design of different components may require them to have individual configuration files residing at specific locations. These configuration files have to be generated from either the values specified by the user in the general configuration file or from the default values specified. Hence, Omnibus GitLab ships with it templates of such configuration files with placeholders which may be filled by default values or values from user. The recipes do the job of completing these templates, by filling them and placing them at necessary locations.

General library methods

Omnibus GitLab also ships some library methods that primarily does the purpose of code reuse. This include methods to check if services are up and running, methods to check if files exist, and helper methods to interact with different components. They’re often used in Chef recipes.

Of all the libraries used in Omnibus GitLab, there are some special ones: the primary GitLab module and all the component-specific libraries that it invokes. The component specific libraries contains methods that do the job of parsing the configuration file for settings defined for their corresponding components. The primary GitLab module contains methods that co-ordinate this. It is responsible for identifying default values, invoking component-specific libraries, merging the default values and user specified values, validating them, and generating additional configurations based on their initial values. Every top level component that’s shipped by Omnibus GitLab package gets added to this module, so that they can be mentioned in configuration file and default attributes and get parsed correctly.

runit

GitLab uses runit recipes for the purpose of service management and supervision. runit recipes do the job of identifying the init system used by the OS and perform basic service management tasks like creating necessary service files for GitLab, service enabling, and service reloading. runit provides runit_service definitions that can be used by other recipes to interact with services, see /files/gitlab-cookbooks/runit for more information.

Services

Additional gitlab-ctl commands

Omnibus, by default, provides some wrapper commands like gitlab-ctl reconfigure and gitlab-ctl restart to manage the GitLab instance. There are some additional wrapper commands that target some specific use-cases defined in the Omnibus GitLab repository. These commands get used with the general gitlab-ctl command to perform certain actions like running database migrations or removing dormant accounts and similar not-so-common tasks.

Tests

Omnibus GitLab repository uses ChefSpec to test the cookbooks and recipes it ships. The usual strategy is to check a recipe to see if it behaves correctly in two (or more) conditions: when user doesn’t specify any corresponding configuration, (i.e. when defaults are used) and when user specified configuration is used. Tests may include checking if files are generated in correct locations, services are started/stopped/notified, correct binaries are invoked, and correct parameters are being passed to method invocations. Recipes and library methods have tests associated with them. Omnibus GitLab also uses some support methods or macros to help in the testing process. The tests are defined compatible for parallelization, where possible, to decrease the time required for running the entire test suite.

Читайте также:  субплевральный ателектаз легкого что это

So, of the components described above, some (such as software definitions, project metadata, and tests) find use during the package building, in a build environment, and some (such as Chef cookbooks and recipes, GitLab configuration file, runit, and gitlab-ctl commands) are used to configure the user’s installed instance.

Work life cycle of Omnibus GitLab

What happens during package building

Caching

Omnibus uses two types of cache to optimize the build process: one to store the software artifacts (sources of dependent softwares), and one to store the project tree after each software component is built

Software artifact cache (for GitLab Inc builds)
Build cache

This cache makes sense only if it is retained across builds. For that, we use the caching mechanism of GitLab CI. We have a dedicated runner which is configured to store its internal cache in an Amazon bucket. Before each build, we pull in this cache ( restore_cache_bundle target in our Makefile), move it to appropriate location and start the build. It gets used by the omnibus until the point of dirtying. After the build, we pack the new cache and tells CI to back it up to the Amazon bucket ( pack_cache_bundle in our Makefile).

Both types of cache reduce the overall build time of GitLab and dependencies on external factors.

Источник

Установка и базовая настройка GitLab

. «Доступные официальные методы установки GitLab»

Установка будет рассмотрена в виде Omnibus package, то есть основным рекомендуемым методом установки GitLab. Соотвественно, вся настройка будет выполняться специфично для Omnibus установки. Установка будет для примера производится на CentOS 7, но она не сильно отличается от установки на другие основанные на RPM или DEB системе пакетов дистрибутивы.

Для простых отказоустойчивых инсталляций с балансировкой нагрузки лучше использовать Docker вариант с использованием swarm, тем более он основан на Omnibus пакете. Но в таком случае необходимо настраивать внешние синзронизирующиеся хранилища и базы данных.

Подготовка

Для полноценной работы нам потребуется сервер и доменное имя. DNS-сервер можно использовать любой: свой или хостера. Важно чтобы записи типа A и AAAA вели на необходимый сервер. IP адрес так же можно использовать, но необходимо чтобы GitLab был доступен по тому же адресу, который прописан у него в конфигурационном файле, потому рекомендуется использовать доменное имя.

Рекомендуется настроить firewall и открыть публично порты 443 (https при использовании SSL), 80 (http), 22 (SSH).

Установка с настройкой GitLab

Установка

Чтобы установить GitLab, необходимо проследовать инструкциям по данной ссылке на официальном сайте. Ниже представлены некоторые комментарии для CentOS 7, но многие вещи применимы и к другим ОС.

1. Install and configure the necessary dependencies

В данном пункте предлагается вначале настроить SSH доступ и настроить фаервол. В принципе делать это необязательно, да и SSH доступ скорее и так включен. По этой причине внизу помечены реально необходимые строки и добавлены правила для фаервола.

Далее необходимо установить Postfix. CentOS/RHEL/Oracle/Scientific не спросят при установке как мы хотим использовать postfix. Debian/Ubuntu спросят, можно выбрать Internet Site и вписать туда доменное имя на котором будет GtiLab.

Если не было окна, предлагающего настроить Postfix, то сделаем это руками.

необходимо поменять gitlab-ee (Enterprise Edition) на gitlab-ce (Community Edition). Так же следует обратить внимание, что данные строки скриптов в инструкциях отличаются только указанием пакетной системы ( rpm или deb ).

Полсле выполнения команды сверху будет добавлен репозиторий и установлено некоторое ПО. Теперь можно установить GitLab:

3. Browse to the hostname and login

Настройка

Настройка админского пользователя

Не стоит сразу ломиться в файл конфигурации. Имеет смысл установить пароль пользователя и при желании сменить логин root на что-то другое, а так же желательно включить двухфакторную аутентификацию.

Если по адресу домена, указанному в прошлом пункте пусто, то проверим правильность строки external_url ‘http://example.com’ в конфигурационном файле /etc/gitlab/gitlab.rb и если там все правильно, то выполним

После данных манипуляций все должно заработать и по указанному URL мы увидим окно с просьбой сменить пароль. Укажем пароль.

В боковой панели есть кнопка Account в которой можно поменять Username и включить двухфакторную аутентификацию.

На данном этапе можно остановиться и настроить все остальное позже под себя.

Настройка SSL и прочих мелочей

В данном документе будут описаны самые необходимые секции по мнению автора, на которые следует обратить внимание. Кроме того, будут опущены не раскомментированные секции в конфигурационном файле (если они закомментированы, то используются стандартные указанные в них значения).

Касательно использования SSL с GitLab стоит посетить другую страницу документации.

Copyright © 2017 Александр Пинегин aka Bloody Foxy

Источник

Configuration options

Configuring the external URL for GitLab

for the change to take effect, run:

Please see our DNS documentation for more details about the use of DNS in a self-managed GitLab instance.

Specifying the external URL at the time of installation

To make it easier to get a GitLab instance up and running with the minimum number of commands, omnibus-gitlab supports the use of an environment variable EXTERNAL_URL during the package installation. On detecting the presence of this environment variable, its value will be written as external_url in the gitlab.rb file as part of package installation (or upgrade).

Configuring a relative URL for GitLab

Note that by changing the URL, all remote URLs will change, so you’ll have to manually edit them in any local repository that points to your GitLab instance.

Relative URL requirements

Starting with 8.17 packages, there is no need to recompile assets.

The Omnibus GitLab package is shipped with pre-compiled assets (CSS, JavaScript, fonts, etc.). If you are running a package before 8.17 and you configure Omnibus with a relative URL, the assets will need to be recompiled, which is a task that consumes a lot of CPU and memory resources. To avoid out-of-memory errors, you should have at least 2GB of RAM available on your system, while we recommend 4GB RAM, and 4 or 8 CPU cores.

Enable relative URL in GitLab

Follow the steps below to enable relative URL in GitLab:

(Optional) If you run short on resources, you can temporarily free up some memory by shutting down Puma and Sidekiq with the following command:

Set the external_url in /etc/gitlab/gitlab.rb :

Reconfigure GitLab for the changes to take effect:

Restart the services so that Sidekiq picks up the changes

If you stumble upon any issues, see the troubleshooting section.

Читайте также:  румынский и молдавский языки какая разница

Disable relative URL in GitLab

To disable the relative URL, follow the same steps as above and set up the external_url to a one that doesn’t contain a relative path.

If you stumble upon any issues, see the troubleshooting section.

Relative URL troubleshooting

If you notice any issues with GitLab assets appearing broken after moving to a relative URL configuration (like missing images or unresponsive components), please raise an issue in GitLab with the Frontend label.

If you are running a version before 8.17 and for some reason, the asset compilation step fails (i.e. the server runs out of memory), you can execute the task manually after you addressed the issue (e.g. add swap):

Loading external configuration file from non-root user

In certain organizations, it is allowed to have access to the configuration files but not as the root user. You can include an external configuration file inside /etc/gitlab/gitlab.rb by specifying the path to the file:

Storing Git data in an alternative directory

You can also add more than one Git data directory by adding the following lines to /etc/gitlab/gitlab.rb instead.

If you’re running Gitaly on its own server remember to also include the gitaly_address for each Git data directory. See the documentation on configuring Gitaly.

Note that the target directories and any of its subpaths must not be a symlink.

Run sudo gitlab-ctl reconfigure for the changes to take effect.

If you already have existing Git repositories in /var/opt/gitlab/git-data you can move them to the new location as follows:

If you’re not looking to move all repositories, but instead want to move specific projects between existing repository storages, use the Edit Project API endpoint and specify the repository_storage attribute.

Changing the name of the Git user / group

By default, Omnibus GitLab uses the user name git for Git GitLab Shell login, ownership of the Git data itself, and SSH URL generation on the web interface. Similarly, the git group is used for group ownership of the Git data.

Run sudo gitlab-ctl reconfigure for the change to take effect.

Note that if you are changing the username of an existing installation, the reconfigure run won’t change the ownership of the nested directories so you will have to do that manually. Make sure that the new user can access repositories as well as the uploads directory.

Specify numeric user and group identifiers

Omnibus GitLab creates users for GitLab, PostgreSQL, Redis and NGINX. You can specify the numeric identifiers for these users in /etc/gitlab/gitlab.rb as follows.

Run sudo gitlab-ctl reconfigure for the changes to take effect.

Disable user and group account management

By default, Omnibus GitLab takes care of creating system user and group accounts as well as keeping the information updated. These system accounts run various components of the package. Most users do not need to change this behavior. However, if your system accounts are managed by other software, eg. LDAP, you might need to disable account management done by the package.

To disable user and group accounts management, in /etc/gitlab/gitlab.rb set:

Warning Omnibus GitLab still expects users and groups to exist on the system where the Omnibus GitLab package is installed.

By default, Omnibus GitLab package expects that following users exist:

By default, Omnibus GitLab package expects that following groups exist:

Moving the home directory for a user

To move an existing home directory, GitLab services will need to be stopped and some downtime is required.

Stop the runit server

Change the home directory. If you had existing data you will need to manually copy/rsync it to these new locations.

Change the configuration setting in your gitlab.rb

Start the runit server

If the runnit service is not stopped and the home directories are not manually moved for the user, GitLab will encounter an error while reconfiguring:

Please make sure to follow the above instructions to avoid this issue.

Disable storage directories management

The Omnibus GitLab package takes care of creating all the necessary directories with the correct ownership and permissions, as well as keeping this updated.

Some of these directories will hold to large amounts of data so in certain setups, these directories will most likely be mounted on an NFS (or some other) share.

Some types of mounts won’t allow automatic creation of directories by the root user (default user for initial setup), eg. NFS with root_squash enabled on the share. To work around this the Omnibus GitLab package will attempt to create these directories using the directory’s owner user.

If you have the /etc/gitlab directory mounted, you can turn off the management of that directory.

In /etc/gitlab/gitlab.rb set:

If you are mounting all GitLab storage directories, each on a separate mount, you should completely disable the management of storage directories.

To disable management of these directories, in /etc/gitlab/gitlab.rb set:

Warning The Omnibus GitLab package still expects these directories to exist on the file system. It is up to the administrator to create and set correct permissions if this setting is set.

Enabling this setting will prevent the creation of the following directories:

Default location Permissions Ownership Purpose
/var/opt/gitlab/git-data 0700 git:git Holds repositories directory
/var/opt/gitlab/git-data/repositories 2770 git:git Holds Git repositories
/var/opt/gitlab/gitlab-rails/shared 0751 git:gitlab-www Holds large object directories
/var/opt/gitlab/gitlab-rails/shared/artifacts 0700 git:git Holds CI artifacts
/var/opt/gitlab/gitlab-rails/shared/external-diffs 0700 git:git Holds external merge request diffs
/var/opt/gitlab/gitlab-rails/shared/lfs-objects 0700 git:git Holds LFS objects
/var/opt/gitlab/gitlab-rails/shared/packages 0700 git:git Holds package repository
/var/opt/gitlab/gitlab-rails/shared/dependency_proxy 0700 git:git Holds dependency proxy
/var/opt/gitlab/gitlab-rails/shared/terraform_state 0700 git:git Holds terraform state
/var/opt/gitlab/gitlab-rails/shared/pages 0750 git:gitlab-www Holds user pages
/var/opt/gitlab/gitlab-rails/uploads 0700 git:git Holds user attachments
/var/opt/gitlab/gitlab-ci/builds 0700 git:git Holds CI build logs
/var/opt/gitlab/.ssh 0700 git:git Holds authorized keys

Only start Omnibus GitLab services after a given file system is mounted

If you want to prevent Omnibus GitLab services (NGINX, Redis, Puma, etc.) from starting before a given file system is mounted, add the following to /etc/gitlab/gitlab.rb :

Run sudo gitlab-ctl reconfigure for the change to take effect.

Configuring runtime directory

When Prometheus monitoring is enabled, GitLab Exporter will conduct measurements of each Puma process (Rails metrics). Every Puma process will need to write a metrics file to a temporary location for each controller request. Prometheus will then collect all these files and process their values.

To avoid creating disk I/O, the Omnibus GitLab package will use a runtime directory.

Источник

Сказочный портал