Prosody: easiest, lightest and fast jabber server written in lua

January 15th, 2017 No comments

Hi there! After long time without any post i’ve come back to you with new experience and few new posts. So today we gonna do install Prosody jabber server to our Linux VPS.

Few month ago a’ve installed Prosody in my server and i was surprised: the setup was really quickly, i edited all configs during 5-10 minutes since i started to do it and afterwards it is really fast and not eating all memory like ejabberd likes do. No more words, let’s begin, guys!

Like everytime, i’ve used CentOS. Let’s install it:

# yum install prosody

We should say “yes” to all packages, that will ask you to install. It is depends packages that necessary for normal Prosody work. Install from repo will fast, so i think we can go to config edit step. I’ve skiped all coments inside config for your comfort and put my own. I described only important things. If you want lern more about Prosody config – just read config’s content. My guide – is for fast install.

admins = { "system@yourdomain.com"  }

modules_enabled = {

-- Generally required

"roster"; -- Allow users to have a roster. Recommended 😉

"saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.

"tls"; -- Add support for secure TLS on c2s/s2s connections

"dialback"; -- s2s dialback support

"disco"; -- Service discovery

-- Not essential, but recommended

"private"; -- Private XML storage (for room bookmarks, etc.)

"vcard"; -- Allow users to set vCards

-- These are commented by default as they have a performance impact

--"privacy"; -- Support privacy lists

--"compression"; -- Stream compression (Note: Requires installed lua-zlib RPM package)

-- Nice to have

"version"; -- Replies to server version requests

"uptime"; -- Report how long server has been running

"time"; -- Let others know the time here on this server

"ping"; -- Replies to XMPP pings with pongs

"pep"; -- Enables users to publish their mood, activity, playing music and more

"register"; -- Allow users to register on this server using a client and change passwords

-- Admin interfaces

"admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands

--"admin_telnet"; -- Opens telnet console interface on localhost port 5582

-- HTTP modules

--"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP"

--"http_files"; -- Serve static files from a directory over HTTP

-- Other specific functionality

"posix"; -- POSIX functionality, sends server to background, enables syslog, etc.

"groups"; -- Shared roster support

--"announce"; -- Send announcement to all online users

--"welcome"; -- Welcome users who register accounts

--"watchregistrations"; -- Alert admins of registrations

--"motd"; -- Send a message to users when they log in

--"legacyauth"; -- Legacy authentication. Only used by some old clients and bots.

};

modules_disabled = {

-- "offline"; -- Store offline messages

-- "c2s"; -- Handle client connections

-- "s2s"; -- Handle server-to-server connections

};

allow_registration = true;

min_seconds_between_registrations = 300;

ssl = {

key = "/etc/prosody/sert/yourdomain.com.key";

certificate = "/etc/prosody/sert/fullchain.cer";

}

c2s_require_encryption = false

s2s_secure_auth = false

authentication = "internal_plain"

storage = "sql" -- Default is "internal" (Note: "sql" requires installed

sql = { driver = "MySQL", database = "databasename", username = "databaseuser", password = "databasepwd", host = "localhost" }

log = {

info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging

error = "/var/log/prosody/prosody.err"; -- Log errors also to file

}

pidfile = "/var/run/prosody/prosody.pid";

Include "conf.d/*.cfg.lua"

It is not finish. You also should create virtualhost for your domain in Prosody. You can edit an exist example.com.cfg.lua or create own one. I just edited an exist example.com.cfg.lua:

VirtualHost "example.com"
ssl = {
        key = "/etc/prosody/sert/example.com.key";
        certificate = "/etc/prosody/sert/fullchain.cer";
}
Component "conference.example.com" "muc"

So as you can see, i implemented 2 things in there. The first is i used mysql database, the second – i wrought path for SSL sertificate. I think that is big deal, because Jabber servers sometimes cant to connect to each other if one of them without SSL-sertificate. So i just used Let’s encrypt. How you can generate it too read in my previously topic. Lets make MySQL data base for our server:

# mysql - root -p
mysql> create database jabber;
mysql> grant usage on *.* to jabber@localhost identified by 'jabberpassword';
mysql> grant all privileges on jabber.* to jabber@localhost ;

So, we just created user and database for MySQL. After that you need to put this data to the Prosody config. You did it, right? Ok, go to the next step. Put Prosody service to autostart:

# systemctl enable prosody

We forgot something. Yes, we definatley forgot something, i see it, but i don’t know what. Oh, i see! Ofcource we forgot to put rules into firewall:

# nano /etc/sysconfig/iptables

Put this rules to file:

-A INPUT -p tcp -m state --state NEW -m tcp --dport 5222 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 5269 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 5223 -j ACCEPT

Yes, that’s so much better! Let’s start this beauty:

# systemctl start prosody

That’s it. You can connect to your new Jabber server and register from client.

All about Let’s encrypt

August 23rd, 2016 No comments

Let’s encrypt – is a free service from google, who allows issue SSL certificates for web projects. Letsencrypt has its own API, through which easily automate the process of re-issue of certificates at the end of their period of validity. Each certificate issued Letsencrypt valid for three months. After that you need issue it again. However, this may occur automatically. Letsencrypt has many implementations to access its API. There is clients written on perl, python, C, bash and also browser clients. I decided use the most simple solution – shell-script called acme.sh. He is able to do all the required things, and does not require installation of additional software system, which is often quite difficult for older systems like FreeBSD.

ssl

As described above, we will use acme.sh script. It is compatible with FreeBSD and all popular distributions of Linux. No need to install additional software, libraries and interpreters.

Download and install

Using curl

curl https://get.acme.sh | sh

Or

wget -O - https://get.acme.sh | sh

Or using git

git clone https://github.com/Neilpang/acme.sh.git
cd ./acme.sh
./acme.sh --install

–install command adding to actual user cron task, which will run few times per week for update sertificates and itself. lets’encrypt ssl sertificates valid 3 months, so cron task is a really important one thing here. I’d recoment do it from user, which can use web-server. For example www-data, or www. or nginx. It depends from your server settings. Anyway it must have write acces to your website directory.

Request sertificate

Below – few fays to get sertificates for domain, and ways to authorise your domain in acme servers.

web-request method

First method – most useful and simple, it allows to get a valid one sertificate for your website immideatley. In two words it is script which sends request to get sertificate for domain, and in the same moment generates csr-request. The server acme answers and give to our script some code, that must be seen from our server and domain. Finally acme server  will connect to your domain, find there html-file with code that was sended to script and make auth succeful. After that, you will receive ssl-serteficate.
So, let’s begin practice. If you use nginx, you have to add one location to your web-site config:

location /.well-known/acme-challenge {
default_type "text/html";
}

Explaination. While authorisation, script for a few seconds puts file with path  /your-site.com/www/.well-known/acme-challenge , and after that acme check it – if file available from web-server then acme will give serteficate to you. So now, if all terms was completed, we can do serteficate request:

acme.sh --issue -d erdees.ru -w /usr/local/www/erdees.ru/

As you can see from command above, we ask script request with –issue key, for domain with -d key, -w declare our project folder. And because of that really important to make sure, that user, from which you ran script can write to website folder. After success authorisation, this file will be deleted by script automaticly. So. i’d like to say that it apears in website folder just for a few seconds.

After command run, in script folder, you will see sertificates: fullchain.cer – serteficate, а erdees.ru.key – key for that. Our serteficate have all needed intermediate and root serteficates, and works without password. So no necessary to do somethinf more – just add it to ypur web server an enjoy your ssl.

DNS authorisation method

This can be useful in few cases. First one – when serteficate needed be added to domain in internal network. For example, i can make DNS-A record to any domain, but with ip 192.168.15.25 . So in that case this method will be very useful. In this case first method will not work because internal ip cannot be listen by acme servers. If you want use this method, you should add some A-record in DNS for your domain with authorisation key. Authorization key you can receive from acme.sh script. Make request:

acme.sh --issue --dns -d erdees.ru --dnssleep 2400

After that command, script print next information (i’ve changed it special for this article):

You should get the output like below:

Add the following txt record:
Domain:_acme-challenge.ssltest.db0.ru
Txt value:9ihDbjYfTExAYeDBHTrecgvrve5o18KBzwvTEjUnSwd32-c

Please add those txt records to the domains. Waiting for the dns to take effect.

So it means that you should add  RR TXT-record to domain erdees.ru with name  _acme-challenge.erdees.ru and value 9ihDbjYfTExAYeDBHTrecgvrve5o18KBzwvTEjUnSwd32-c (each request has own value, it’s just example). After that, i’ll recommend you wait about 15-20 minutes, and run next command:

acme.sh --renew -d erdees.ru

acme will check dns record of your dns, and if we did al things correctly, script will give you serteficate. Next steps will same as in first recipe.

Standalone method

I’d not recommend this method to use, because you should turn off your website while script works. In many cases it is very uncomfortable and you may lost your site users. Soo if you wan use it anyway, first turn off your web-server which listen 80 and 433 port in internet.  It will not work without . Next, enter command

acme.sh --issue --standalone -d ssltest.db0.ru

You will receive serteficate, so time to turn on web server back.

Another script functions

Script has many useful and good options. You can show all of them – just type  –help. Frome good options script supports update, and also has parameter –sertpath, which allows copy sertificates to nginx folder, for example. While you make request typing command in acme.sh script, you can use -d key and create request to many domains in one time. In 5-10 domains, if you necessary. Script creates to actual user cron task, which will run few times per week for renew sertificates and update itself.

Meet the systemd, or short introduction

April 10th, 2016 No comments

systemd – is initialization system for other demons to Linux, which came to replace the previously used /sbin/init. Its special feature is the intensive parallelization while start services at boot time, which can significantly speed up the launch of the operating system.
The name comes from the Unix suffix «d» to the demon (c) Wikipedia. In this article, we will speak only about CentOS, but of course, this will also be true for other systems.

A problem often encountered in systemd, when even with seemingly correct configuration, the service does not start. Looking through the logs, you can understand that mistakes are usually standard – for the example of httpd he can not listen to the port, or resolve ldap user. After many experiments, we found the optimal configuration scripts that run in servers correctly.
All startup scripts are in the directory /lib/systemd/system

Apache

The file is called httpd.service. The problem is that he did not work until until network subsystem will not loaded and resolving ldap users. For Apache start network-online.target, nss-lookup.target and nss-user-lookup.target must be loaded before Apache. It is easy to understand, if you take a look on config file below:

[Unit]
Description = The Apache HTTP Server
After = network-online.target remote-fs.target nss-lookup.target nss-user-lookup.target
Documentation = man: httpd (8)
Documentation = man: apachectl (8)

[Service]
Type = notify
EnvironmentFile = /etc/sysconfig/httpd
ExecStart = /usr/sbin/httpd $ OPTIONS -DFOREGROUND
ExecReload = /usr/sbin/ httpd $ OPTIONS -k graceful
ExecStop = /bin/kill -WINCH $ {MAINPID}
KillSignal = SIGCONT
PrivateTmp = true

[Install]
WantedBy = multi-user.target

Configuring Apache additional instances in systemd

In order to configure Apache to work on multiple ports at once (additional instances or “profiles”), you need to do a little creative action.

Create Apache configs

Additional Apache will listen to another port, so we need an another config file, which will be described. For example, here is this one.

Listen 192.168.150.214:8001
Include conf/Includes/ *. Conf
Include conf/hosting/ *. Conf
Include conf/vhosts/ *. Conf

CustomLog "/var/log/apache/access1.log" combined env =! Dontlog
ErrorLog "/var/log/apache/error1.log"

User apache
Group apache

PidFile /var/run/httpd/httpd1.pid

You must specify a folder with our configs, by analogy with the standard the httpd.conf, be sure to rename the name of the log, enter the user/group of the web server and the pid-file. In fact nothing more is needed for configuration. Let’s call httpd1.conf file for port 8001, httpd2.conf for port 8002 and then more, by analogy, if you need more.

Edit files with parameters

To get started, copy a file from the folder / etc / sysconfig

# Cp httpd httpd1

If you need to do more profiles, copy as needed.
Next, edit the copied a file. Do not touch the default file. All that should be in it, it’s two lines:

OPTIONS = -f conf / httpd1.conf
LANG = C

More, in fact, do not need anything. As you guessed, conf / httpd1.conf is a workpiece Apache config, which we did in the preceding paragraph.

Make and run the service

So, go to the folder with start scripts systemd

# Cd /lib/systemd/system

Copy the current service and a file called names by analogy with configs and files from the sysconfig

# Cp httpd.service httpd1.service.

Edit the config file which we COPIED before, leaving intact a default one

# EnvironmentFile = /etc/sysconfig/httpd

Replace the created us

# EnvironmentFile = /etc/sysconfig/httpd1

Save, switch service on

# Systemctl enable httpd1

Run it

# Systemctl start httpd1.service

Or so – also fulfills

# Systemctl start httpd1

So, you have additional instance Apache.

nginx

nginx.service adjusted by analogy – the main thing that against official documentation in “After” was present network-online.target. Also, it is important (applies also, and apache) remote-fs.target option – any occurred after loading it as a Web server files can take, for example, GlusterFS.

[Unit]
Description = The NGINX HTTP and reverse proxy server
After = syslog.target network-online.target remote-fs.target nss-lookup.target

[Service]
Type = forking
PIDFile = /run/nginx.pid
ExecStartPre = /usr/sbin/nginx -t
ExecStart = /usr/sbin/nginx
ExecReload = /bin/kill -s HUP $ MAINPID
ExecStop = /bin/kill -s QUIT $ MAINPID
PrivateTmp = true

[Install]
WantedBy = multi-user.target

Zabbix

Similarly configs web server, you need to change in the default script

After = network.target
On
After = network-online.target

Commands

For easy management, systemd has a large number of commands. Know all of them is not necessarily, but here is a list of basic and necessary good to know.

List

In the case if you edited boot scripts and other components systemd, you can restart it by command:

systemctl daemon-reload

Generate a report on the boot systemd and put it in a file (by the way, it is very useful for understanding the operation of systemd)

systemd-analyze plot> /home/vtorov/boot.svg

Take a look what services are loaded in systemd, or enabled while system start

systemctl list-units --type service

As above, but more and shows the “Target”

systemctl list-units

Switching on and off, reload/restart the service, or other actions (see them below)

systemctl <action> <object>

That is, for example,

systemctl restart httpd

Where restart is an action, but httpd is an object. The list of actions below.

Actions

reload
restart
enable
disable
stop
start
status

By the way, old chkconfig, redirecting their actions into systemd, but because it will soon be expelled from the CentOS, then to use it is not necessary to devote more time and systemd.

mmonit: monitoring / response system

November 6th, 2015 No comments

mmonit – server monitoring system, able to perform at an event specified in the config scripts. For example, restart the service \ daemon when it drops or stops working, send notifications, run the daemon with a certain parameter and more.

Setup

Installation is simple. For FreeBSD:

# cd /usr/ports/*/monit

Add to autostart:

# echo 'proftpd_enable="YES"' >> /etc/rc.conf

For CentOS:

# yum install monit -y

Add to autostart:

# chkconfig monit on

Next, we have to set monitoring objects. For each service has own configuration, because different services are monitored in different ways. This can be checked by .pid-file approach to the url or checking port availability, type telnet commands, and more.

Configs for different services

Main file that describes the monitoring objects – it monitrc_local. Let’s divide it into two parts content: first part – mandatory, which must be everywhere, including our settings. The second part – according to the description of the service that you want to monitor. The first part of the config:

set daemon 120 with start delay 5 # time, after monit starts checking
set logfile /var/log/monit.log # log file
set mailserver mail.domain.com, localhost # your mail-server

set alert monit@domain.com # your admin mail. monit will send you notofications

set httpd port 2812 and # protocol and monit's web-interface
use address srv21.domain.local # server's hostname (use own one)
signature disable
allow localhost # allow localhost 🙂
allow 192.168.0.0/255.255.0.0 # allow acces from this subnetworks
allow @users # allow this @group
allow monit:monitadmin # allow user:password

Next, in this file below, you can find monitoring policies. For each servers they are different.

For Apache

We will see for Apache via .pid and page availability (url).
Config for this:

check process apache with pidfile /var/run/httpd.www.pid # check .pid-файл
group www # monitoring group 
start program = "/usr/local/etc/rc.d/apache22 start" with timeout 50 seconds # command for start cervice
stop program = "/usr/local/etc/rc.d/apache22 stop" with timeout 50 seconds # command for stop service
if failed host lst207.b.ls1.ru port 8000 # if url will not available /monit/token on port 8000 then
protocol HTTP request "/monit/token" with timeout 30 seconds then restart # restart service after 30 seconds

For nginx

Monitoring for nginx almost the same like for Apache. Difference only in service port.

check process nginx with pidfile /var/run/nginx.pid # check .pid-file
group www # monitoring group
start program = "/usr/local/etc/rc.d/nginx start" # command for start service
stop program = "/usr/local/etc/rc.d/nginx stop" # command for stop service
if failed host lst207.b.ls1.ru port 80 # if url will not available /monit/token on port 8000 then
protocol HTTP request "/monit/token" with timeout 20 seconds then restart # restart service 30 second

For redis

redis monitored much more interesting than the web server: it comes to telnet on redis port, enters commands and expects definite answer. If the answer is yes, monit does not perform any action. If the answer is no, monit will restart redis. Here is config file:

 

check process redis.service match "redis-server" # looking for processes with name
group db # monitoring group
start program = "/usr/local/etc/rc.d/redis start" with timeout 50 seconds # command for start service
stop program = "/usr/local/etc/rc.d/redis stop" with timeout 50 seconds # command for stop service
if failed
port 6379 # port redis
send "SET MONIT-CHECK ok\r\n" # send message
expect "OK" # wait for answer
send "EXISTS MONIT-CHECK\r\n" # send message
expect ":1" # wait for answer
then restart # restart
if 5 restarts within 5 cycles then timeout # timeout after 5 restarts and 5 cycles

For Gearman

check process gearmand with pidfile /var/run/gearmand/gearmand.pid
group gearmand
start program = "/usr/local/etc/rc.d/gearmand start"
stop program = "/usr/local/etc/rc.d/gearmand stop"
if failed host 127.0.0.1 port 4730 then restart
if 5 restart within 5 cycles then timeout
Categories: IT-bullshit, System administration Tags:

Настройка репозитория FreeBSD poudriere

November 6th, 2015 No comments

Poudriere (фр. пороховая бочка) – удобное средство для полной автоматизации репозитория FreeBSD. Работает как с pkg_* так и с pkgng. Все пакеты poudriere собирает во временных клетках, что бы не навредить целевой системе. Работает только на мастер-серверах из-за использования jail. Из дополнительных возможностей – возможность поддерживать одновременно репозитории для разных версий и архитектур FreeBSD.

Установка

Устанавливается из портов. Особых замечаний нет, всё происходит по-умолчанию.

# cd /usr/ports/ports-mgmt/poudriere
# Make install clean

Настройка

Директории pouriere. Их две, первая /usr/local/poudriere содержит данные (клетки, порты, откомпилированные пакеты) вторая – настройки и /usr/local/etc/poudriere.d. Далее настраиваем основной конфиг /usr/local/etc/poudriere.conf. Он хорошо закомментирован, однако лучше я напишу несколько пояснений.

NO_ZFS=yes # Не использовать ZFS - да, не использовать
FREEBSD_HOST=http://ftp.freebsd.org # Пакеты берём отсюда
RESOLV_CONF=/etc/resolv.conf # Файл resolv
BASEFS=/usr/local/poudriere # Папка с данными
USE_PORTLINT=no Использовать portlint или нет
USE_TMPFS=yes # Использовать tmpfs
DISTFILES_CACHE=/usr/ports/distfiles # Кеш дистфайлов
CHECK_CHANGED_OPTIONS=verbose # проверять изменены ли опции сборки пакетов (если да, то будет пересборка пакета при изменении опций)
CHECK_CHANGED_DEPS=yes # проверять изменялись ли зависимости пакета
PKG_REPO_SIGNING_KEY=/etc/ssl/keys/repo.key # Ключик. Можно и без него
PREPARE_PARALLEL_JOBS=4 # Число параллельных операций (сборок, билдеров)
NOLINUX=yes # Без Linux 

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

Как сказано выше, пакеты собираются в клетках с указанием дерева портов. Имена клетки и портов обязательно должны совпадать, будьте внимательны при их создании! Если в будущем при сборке не указывать название дерева портов, то сборка будет происходить из стандартных портов poudriere. По этому, если они ещё не созданы, их будет необходимо создать.
Создание дерева портов

Ключ -c означает создать, -p имя порта

# poudriere ports -c -p FreeBSD-10.1

Создадим дерево портов по-умолчанию:

# poudriere ports -c -p default

Используется в том случае, если мы начнём сборку, не указав специализированные порты.
Создание клетки

Ключ -c означает создать, -j означает имя клетки, -v – версия FreeBSD, -a – архитектуру

# poudriere jail -c -j FreeBSD-10.1 -v 10.1-RELEASE -a amd64

Настройка собираемых пакетов

Poudriere позволяет делать сборку как всего дерева портов, так и по отдельности. Все порты нам пока не нужны (однако далее я всё-таки напишу как это сделать).
Что собирать

Соберём только то, что нам необходимо для работы. Для этого создадим файл

# touch /usr/local/etc/poudriere.d/pkglist.txt

И на каждой новой строчке вставим имена необходимых пакетов. Например, правильное содержание файла:

www/apache24 
www/nginx 
www/mod_php56
lang/php56 
lang/php56-extensions
devel/pcre
devel/apr1
shells/bash

То есть, правильный формат файла – порт/имя_пакета . Никакие другие параметры вписывать нельзя.
Настройка опций компиляции

Само собой, опции компиляции по-умолчанию много кому не подойдёт. Для этого у Poudriere предусмотрена специальная утилита, которая позволяет задавать параметры сборки на каждый пакет. Сделать это необходимо один раз, после чего в папке /usr/local/etc/poudriere.d/ появится папка options, которая будет содержать параметры компиляции для каждого собираемого порта (будущего пакета). Если этого не делать, то компиляция может происходить каждый раз. Нам же нужно, что бы это происходило только тогда, когда обновился порт для определённого пакета.

Для того, что бы задать параметр сборки для отдельного пакета. При выполнении команды, описанной ниже, появится диалоговое псевдо-графическое окно, аналогичное make config. Для этого нужно выполнить:

# poudriere options -c lang/php56-extensions

Однако, мы имеем файл со списком пакетов, и задавать вручную на каждый пакет опции командой не совсем удобно. Для этого, укажем для poudriere options файл, и нам будет предложено ввести параметры сборки для каждого указанного в файле пакета. Параметр -c означает предлагать ввести параметры в любом случае, даже если они уже заданы.

# poudriere options -сf /usr/local/etc/poudriere.d/pkglist.txt

Обновление портов и сама сборка пакетов

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

Обновим порты. Параметр -p означает название дерева портов, -u – update

# poudriere ports -p FreeBSD-10.1 -u

Начнём сборку пакетов. Опция -f означает, что мы будем собирать пакеты, указанные в нашем файле, который мы подготовили в предыдущих шагах. Параметр -p означает имя дерева портов, -j имя джейла. Имена клетки и портов обязательно должны совпадать, будьте внимательны при их создании!

poudriere bulk -f /usr/local/etc/poudriere.d/pkglist.txt -p FreeBSD-10.1 -j FreeBSD-10.1

После выполнения этой команды начнётся сборка. За её прогрессом можно наблюдать из консоли, вывод достаточно информативен. Если не хватает информации, и хочется больше – можно нажать сочетание клавиш Ctrl+t. После отработки команды, poudriere выдаст небольшой отчёт о количестве собранных пакетов, о пакетах с ошибками, если они есть и прочую необходимую информацию.

Когда сборка закончится, все пакеты будут доступны в папках /usr/local/poudriere/data/packages/{имя клетки которая была создана для сборки в poudriere }. Папка будет в точности повторять структуру официального репозитория FreeBSD, и включать необходимые для клиентов файлы – meta.txz, packagesite.txz и другие. Эти файлы будут генерироваться при каждой сборке. Для обновления клиентов вполне достаточно сделать эту папку видимой из веб сервера, настроив autoindex в Apache или nginx. При использовании опции -f <file> пакеты будут собираться при условии, если они не были до этого собраны, или если обновилось соответствующая ветка порта. Можно использовать параметр -c который будет собирать пакеты в любом случае, однако по непонятной причине очень часто после использования опции -c при сборке, в следующий раз будет пересобираться весь список пакетов. По этому пользоваться опцией я рекомендую с осторожностью.
Настройка веб-интерфейса

Poudriere по умолчанию содержит удобный и функциональный веб-интерфейс, который будет удобно для контроля сборки пакетов, просмотра статуса, и выгрузки ошибок. Для его настройки не нужно ничего качать, настраивать и конфигурировать – нужно просто настроить конфиг для веб-сервера. Не нужен даже php, система работает на html + динамической выгрузке данных из json. Работающий пример можно посмотреть тут: http://poudriere.ls1.ru/

Конфиг для nginx:

server {

listen 192.168.102.250:80;
server_name poudriere.ls1.ru;

# Point to the web-fronted
location / {
root /usr/local/share/poudriere/html/;
index index.html index.htm;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/www/nginx-dist;
}

# This location is used by the web-interface
location /data {
alias /usr/local/poudriere/data/logs/bulk;
autoindex on;
}

# Use this as the base URL to serve packages via http
location /packages {
root /usr/local/poudriere/data/;
index index.html;
}

}

Автоматизировать процесс

Поскольку все пакеты заранее сконфигурированы, то сборку можно автоматизировать, добавив задание в /etc/crontab на обновление и сборку портов:

0 0 * * * root /usr/local/bin/poudriere ports -p FreeBSD-10.1 -u
0 0 * * * root /usr/local/bin/poudriere bulk -f /usr/local/etc/poudriere.d/pkglist.txt -p FreeBSD-10.1 -j FreeBSD-10.1

Полезные команды и опции

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

# poudriere jail -l

Аналогично для просмотра портов:

# poudriere ports -l

Как обновляться

Для настройки репозитория на конечной системе (пока только 10.1):

 

# ee /etc/pkg/FreeBSD.conf

FreeBSD: {
url: http://mirror.ls1.ru
enabled: true,
}

После этого сделать:

# pkg upgrade

Или если не хочется отвечать на вопрос, можно сделать автоматически:

# env ASSUME_ALWAYS_YES=YES /usr/sbin/pkg bootstrap

Система полностью готова к работе с репозиторием, можно ставить и обновлять из него пакеты.

Categories: IT-bullshit, System administration Tags: