CentOS: создание локального репозитория

Автор: | 17/01/2015
 

centos-logo-new-4В наличии имеется 8 серверов, и очень печальный канал в мир.

Что бы уменьшить нагрузку, и ускорить процесс – можно создать отдельный репозиторий на одной машине, которая будет обновлять в нём пакеты, и потом раздавать обновления другим машинам в сети.

Настройка выполняется на CentOS 6.6.

Список зеркал (как HTTP, так и rsync) можно найти тут>>>.

Создаём каталоги для репозитория:

# mkdir -pv /repository/CentOS/6.6/{os,updates}/i386
mkdir: created directory `/repository/CentOS'
mkdir: created directory `/repository/CentOS/6.6'
mkdir: created directory `/repository/CentOS/6.6/os'
mkdir: created directory `/repository/CentOS/6.6/os/i386'
mkdir: created directory `/repository/CentOS/6.6/updates'
mkdir: created directory `/repository/CentOS/6.6/updates/i386'

Кратко о структуре директорий в репозитории.

  • [Base] – обычно хранится в директории os, содержит в себе пакеты, находящиеся в релизном выпуске системы;
  • [Updates] – обычно хранится в директории updates, содержит в себе более новые по отношению к [Base] пакеты.

Сейчас нам требуются только эти два. Описание других можно найти тут>>>.

Подключаем образ DVD, что бы не качать всё из сети:

# mount /dev/sr0 /mnt/dvd/
mount: block device /dev/sr0 is write-protected, mounting read-only

Копируем содержимое диска в директорию /repository/CentOS/6.6/os/i386/:

# rsync -avP /mnt/dvd/ /repository/CentOS/6.6/os/i386
...
sent 4665734457 bytes  received 80394 bytes  8178466.00 bytes/sec
total size is 4664826015  speedup is 1.00

Подключаем DVD2, и повторяем, но копируем только rpm-файлы:

# umount /mnt/dvd/
# mount /dev/sr0 /mnt/dvd/
# rsync -avP /mnt/dvd/Packages/ /repository/CentOS/6.6/os/i386/Packages/

Общий размер получился:

# du -sh /repository/CentOS/6.6/os/i386/
4.8G /repository/CentOS/6.6/os/i386/

На загрузку файлов с дисков ушло ~15 минут.

Если же подключить диск возможности нет – можно скачать [Base] с зеркала.

Выбираем сервер, проверяем его содержимое:

# rsync rsync://mirror.besthosting.ua/CentOS/6.6/os/
drwxrwxr-x        4096 2014/10/21 19:56:44 .
drwxr-xr-x        4096 2014/10/24 17:13:57 i386
drwxr-xr-x        4096 2014/10/24 17:13:12 x86_64
# rsync rsync://mirror.besthosting.ua/CentOS/6.6/os/i386/
drwxr-xr-x 4096 2014/10/24 17:13:57 .
-rw-r--r-- 31 2014/10/24 17:13:56 .discinfo
-rw-r--r-- 360 2014/10/24 17:13:55 .treeinfo
-rw-rw-r-- 14 2014/10/24 16:59:05 CentOS_BuildTag
-rw-rw-r-- 212 2013/11/27 11:36:04 EULA
-rw-rw-r-- 18009 2013/11/27 11:36:04 GPL
-rw-rw-r-- 1354 2014/10/19 18:59:28 RELEASE-NOTES-en-US.html
-rw-rw-r-- 1706 2013/11/27 11:36:04 RPM-GPG-KEY-CentOS-6
-rw-rw-r-- 1730 2013/11/27 11:36:04 RPM-GPG-KEY-CentOS-Debug-6
-rw-rw-r-- 1730 2013/11/27 11:36:04 RPM-GPG-KEY-CentOS-Security-6
-rw-rw-r-- 1734 2013/11/27 11:36:04 RPM-GPG-KEY-CentOS-Testing-6
drwxr-xr-x 327680 2014/10/24 20:28:16 Packages
drwxr-xr-x 4096 2014/10/24 17:13:55 images
drwxr-xr-x 4096 2014/10/24 17:12:17 isolinux
drwxr-xr-x 4096 2014/10/24 16:59:05 repodata

И начинаем загрузку:

# rsync -avrt rsync://mirror.besthosting.ua/CentOS/6.6/os/i386/ /repository/CentOS/6.6/os/i386/

Репозиторий [Base] готов. Утилита createrepo потребуется только в том случае, если вы хотите создавать свой репозиторий со своими пакетами.

Так как мы копировали данные с диска или сети – все метаданные для репозитория уже есть в каталоге /repository/CentOS/6.6/os/i386/repodata/:

# ls -l /repository/CentOS/6.6/os/i386/repodata/
total 21572
-r--r--r-- 1 root root 5337502 Oct 24 17:17 32d64987a8ddfaec2ef96157eecb6de32cd078a30ccdd22ca0d60ccc8860497f-filelists.sqlite.bz2
-r--r--r-- 1 root root 4823415 Oct 24 17:17 375c8875b94c3412147ee2f231a69312f69a1ac94408ae85ff05973e198265cf-filelists.xml.gz
-r--r--r-- 1 root root  219089 Oct 24 17:17 431e20dbdba740c9a59dff997a4e18b689531ce29c843d6e55bdc801a1bdf412-c6-i386-comps.xml.gz
-r--r--r-- 1 root root 3708827 Oct 24 17:17 58c6bae3c98b6582453b524f1d75cec03224efbf772fc398cc525f5e1c185e05-primary.sqlite.bz2
-r--r--r-- 1 root root 2099435 Oct 24 17:17 58dc1f3464d59a20ed57ee892d1ad1fb966b9397d0f7e2e4d21a4bfbe882e190-primary.xml.gz
-r--r--r-- 1 root root 2456105 Oct 24 17:17 76277740057683f0f4a1ba2e692eafa2250f1def2b73e2e7d7e9bd40ad9b6317-other.xml.gz
-r--r--r-- 1 root root 1202377 Oct 24 17:17 9af14623fb0e3420f6256420a4ff5668dc0f5964bac2ea71f2c5b338d3c7ecb7-c6-i386-comps.xml
-r--r--r-- 1 root root 2218282 Oct 24 17:17 fe0cd0f63a552a431cac0595332beb91fc67d75416f49ba2eb968c065dea058c-other.sqlite.bz2
-r--r--r-- 1 root root    4057 Oct 24 17:17 repomd.xml
-r--r--r-- 1 root root    2571 Oct 24 17:17 TRANS.TBL

Приступаем к [Updates]. Содержимое будем загружать с зеркала.

Проверяем сервер:

# rsync rsync://mirror.besthosting.ua/CentOS/6.6/updates/i386/
drwxrwxr-x 4096 2014/10/24 19:10:18 .
drwxrwxr-x 36864 2015/01/15 00:36:09 Packages
drwxrwxr-x 131072 2015/01/15 00:36:09 drpms
drwxrwxr-x 4096 2015/01/15 00:36:15 repodata

И загружаем данные в каталог updates:

# rsync -avrt rsync://mirror.besthosting.ua/CentOS/6.6/updates/i386/ /repository/CentOS/6.6/updates/i386/
...
sent 31469 bytes received 2900595269 bytes 5436976.08 bytes/sec
total size is 2900070091 speedup is 1.00
# du -sh /repository/CentOS/6.6/updates/i386/
2.8G /repository/CentOS/6.6/updates/i386/

По времени заняло ~10 минут.

Репозитории готовы.

Создаём файл конфигурации нашего репозитория /etc/yum.repos.d/local.repo:

[local-base]
name=Local - Base
# для проверки - устанавливаем локальный адрес
# baseurl=http://repo.local.net/6.6/os/$basearch/
baseurl=file:///repository/CentOS/6.6/os/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-6

[local-update]
name=Local - Updates
# baseurl=http://repo.local.net/6.6/updates/$basearch/
baseurl=file:///repository/CentOS/6.6/updates/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-6

И проверяем:

# yum repolist
...
local-base               Local - Base                     4,926
local-update             Local - Updates                  565
...

Репозиторий работает.

Проверяем обновления, отключив все репозитории, кроме нашего нового [Updates]:

# yum --disablerepo=* --enablerepo=local-update check-update
Loaded plugins: downloadonly, fastestmirror, security
Loading mirror speeds from cached hostfile

bind-libs.i686                              32:9.8.2-0.30.rc1.el6_6.1                        local-update
cyrus-sasl-gssapi.i686                      2.1.23-15.el6_6.1                                local-update
...

Работает.

Далее, что бы открыть доступ к репозитория для других серверов – настраиваем NGINX (или Apache HTTP, но у меня везде NGINX).

К примеру, репозиторий будет находится по адресу http://repo.local.net.

Создаём файл /etc/nginx/conf.d/repo.local.net.conf с таким содержимым:

server {
    listen        80;
    server_name   repo.local.net  www.repo.local.net;
    access_log    /var/log/nginx_access.log;
    error_log     /var/log/nginx_error.log;
    root          /repository/CentOS;
}

Проверяем, перезапускаем:

# nginx -t && service nginx restart
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Stopping nginx:                                            [  OK  ]
Starting nginx:                                            [  OK  ]

Далее, возвращаемся к файлу настроек репозитория, и меняем:

#baseurl=http://repo.local.net/6.6/os/$basearch/
baseurl=file:///repository/CentOS/6.6/os/$basearch/

На:

baseurl=http://repo.local.net/6.6/updates/$basearch/
#baseurl=file:///repository/CentOS/6.6/updates/$basearch/

Теперь вместо обращения напрямую к локальной директории – YUM будет отправлять запрос по HTTP.

Проверяем:

# yum repolist
...
local-base                    Local - Base                     4,926
local-update                  Local - Updates                  565
...

В случае ошибок вида:

Error importing repomd.xml for update: Damaged repomd.xml file

В первую очередь пробуем получить файл по HTTP:

# curl http://repo.local.net/repository/CentOS/6.6/os/i386/repodata/repomd.xml

И смотрим ошибки веб-сервера.

Устанавливаем новый репозиторий (файл local.repo) на других серверах.

Последний шаг – настроить обновление пакетов в [Updates].

Сделаем простой скрипт /etc/cron.daily/reposupdate.sh:

#!/bin/bash

rsync="/usr/bin/rsync -azvrt --delete --delay-updates"
mirror="rsync://mirror.besthosting.ua/CentOS"
ver=6.6
arch="i386"
baselist="os updates"
path=/repository/CentOS/
log="/var/log/repoudate.log"

for base in $baselist; do
    remote=$mirror/$ver/$base/$arch/
    $rsync $remote $path/$ver/$base/$arch/ | tee -a $log
done

Последний момент, который стоит уточнить. Во всех примерах выше – загрузка пакетов делается из директории 6.6, тогда как на зеркалах есть директория 6:

 # rsync rsync://mirror.besthosting.ua/CentOS/6/
drwxrwxr-x        4096 2014/10/20 00:36:15 .
drwxr-xr-x        4096 2014/10/20 00:36:15 SCL
drwxrwxr-x        4096 2014/10/20 12:36:56 centosplus
...

Можно обновляться из него (обязательно и [Base] и [Updates]), тогда система обновится при выходе новой версии, например, 6.7 (хотя такой уже не будет, наверно).

Так же образом – добавляются репозитории Elrepo, RPMforge и другие.

Ссылки по теме:

http://www.totalnetsolutions.net

http://giechelbit.duister.org