Home > IT-bullshit > Ставим связку rtorrent+rutorrent на сервере с virtualmin

Ставим связку rtorrent+rutorrent на сервере с virtualmin

Потратив прилично времени за гуглом, я все-таки смог поставить веб-интерфейс rutorrnet для торрент клиента rtorrent.

Да, я сделал это не идеально, но как говориться первый блин комом.

Сразу же расскажу о граблях, на которые можно наступить. Шишки на моей голове говорят, что это возможно.

1. Если у вас уже используется виртуалмин (а может быть даже и вебмин), не надо ставить пакет lighttpd – может некорректно заработать SCGI модуль, соединяющий веб-интерфейс с самим торрентом

2. Можно использовать стандартные пакеты rtorrent и xmlrpc-c, как написано ниже, а можно собрать их из исходников. Я использовал стандартные и все работает. Из минусов: Параметр “отдано” пишется в килобайтах и не переводится в гигабайты. О том как собрать из исходников читайте в конце статьи.

Эта инструкция написана, для установки связки rtorrent+rutorrent при уже установленных virtualmin+webmin.
Качалка торрентов будет запускаться от имени пользователя, созданного Виртуалмином. Например, вы уже создали сайт example.ru , а Виртуалмин соответственно создал пользователя example.
Во время всей установки меняйте во ВСЕХ нижеприведенных кодах example на своего юзера/сайт.

Ставим необходимый модуль для Апача

$ sudo apt-get install libapache2-mod-scgi

Правим конфиг апача

$ sudo nano /etc/apache2/apache2.conf

Дописываем в конец файла:

# rutorrent
LoadModule scgi_module /usr/lib/apache2/modules/mod_scgi.so
SCGIMount /RPC2 127.0.0.1:5000

Перезапускаем апач

$ sudo service apache2 restart

Если по каким-либо причинам вы получите ошибку “could not find scgi.so” тогда просто сделайте:

$ sudo find / -iname “*scgi*so”

И допишите найденный путь в конфигурацию апача вместо старой

Ставим rutorrent и плагины. Переходим в директорию:

$ cd /home/example/public_html

Скачиваем tar архив. На момент написания последней была версия 3.4. Посмотреть есть ли более свежая версия можно тут .

$ wget http://rutorrent.googlecode.com/files/rutorrent-3.4.tar.gz

Распаковываем его:

$ tar -xvzf rutorrent-*

Удаляем теперь уже не нужный архив

$ rm rutorrent*.gz

Ставим плагины rutorrent:

$ cd /home/example/public_html/rutorrent/plugins
$ svn co http://rutorrent.googlecode.com/svn/trunk/plugins/diskspace
$ svn co http://rutorrent.googlecode.com/svn/trunk/plugins/erasedata
$ svn co http://rutorrent.googlecode.com/svn/trunk/plugins/scheduler
$ svn co http://rutorrent.googlecode.com/svn/trunk/plugins/trafic

Правим конфиг rutorrent:

$ sudo nano /home/examle/public_html/rutorrent/conf/config.php

Убеждаемся, что там есть такие строчки и они совпадают с тем адресом, который мы прописали в конфиге апача:

scgi_port = 5000;
scgi_host = “127.0.0.1”;

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

rTorrent скомпилирован с некорректной версией библиотеки xmlrpc-c, без поддержки 8-байтовых целых. Версия библиотеки должна быть >= 1.11. Часть функциональности будет недоступна.

Но меня это вполне устраивает, поэтому я скачал из стандартных репозитариев:

$ sudo apt-get install rtorrent

И получил такой результат:

Следующие НОВЫЕ пакеты будут установлены:
  libcurl3{a} libssh2-1{a} libtorrent11{a} libxmlrpc-c3{a} rtorrent

Cоздаем папки:

$ sudo mkdir /home/example/torrent/dowload

Здесь будут лежать скачанные торренты:

$ sudo mkdir /home/example/torrent/session

Создаем файл настройки:

$ nano /home/example/.rtorrent.rc

со следующим содержанием

# This is an example resource file for rTorrent. Copy to
# ~/.rtorrent.rc and enable/modify the options as needed. Remember to
# uncomment the options you wish to enable.

# Maximum and minimum number of peers to connect to per torrent.
min_peers = 40
max_peers = 100

# Same as above but for seeding completed torrents (-1 = same as downloading)
min_peers_seed = 40
max_peers_seed = 70

# Maximum number of simultanious uploads per torrent.
max_uploads = 15

# Global upload and download rate in KiB. “0” for unlimited.
download_rate = 2000
upload_rate = 600

# Default directory to save the downloaded torrents.
directory = /home/example/torrent/download

# Default session directory. Make sure you don’t run multiple instance
# of rtorrent using the same session directory. Perhaps using a
# relative path?
session = /home/examle/torrent/session

# Watch a directory for new torrents, and stop those that have been
# deleted.
schedule = watch_directory,5,5,load_start=/home/example/torrent/*.torrent
schedule = untied_directory,5,5,stop_untied=

# For trafic plugin
schedule = trafic,10,00:15:00,”execute = {sh,-c,/usr/bin/php /home/example/public_html/rutorrent/php/initplugins.php example &}”
# For scheduler plugin
schedule = scheduler,10,00:15:00,”execute = {sh,-c,/usr/bin/php /home/examle/public_html/rutorrent/php/initplugins.php example &}”

# Close torrents when diskspace is low.
#schedule = low_diskspace,5,60,close_low_diskspace=100M

# The ip address reported to the tracker.
#ip = 127.0.0.1
#ip = rakshasa.no

# The ip address the listening socket and outgoing connections is
# bound to.
#bind = 127.0.0.1
#bind = rakshasa.no

# Port range to use for listening.
port_range = 6890-6999

# Start opening ports at a random position within the port range.
port_random = no

# Check hash for finished torrents. Might be usefull until the bug is
# fixed that causes lack of diskspace not to be properly reported.
check_hash = no

# Set whetever the client should try to connect to UDP trackers.
use_udp_trackers = yes

# Alternative calls to bind and ip that should handle dynamic ip’s.
#schedule = bind_tick,0,1800,bind=rakshasa

# Encryption options, set to none (default) or any combination of the following:
# allow_incoming, try_outgoing, require, require_RC4, enable_retry, prefer_plaintext
#
# The example value allows incoming encrypted connections, starts unencrypted
# outgoing connections but retries with encryption if they fail, preferring
# plaintext to RC4 encryption after the encrypted handshake
#
# encryption = allow_incoming,enable_retry,prefer_plaintext

# Enable DHT support for trackerless torrents or when all trackers are down.
# May be set to “disable” (completely disable DHT), “off” (do not start DHT),
# “auto” (start and stop DHT as needed), or “on” (start DHT immediately).
# The default is “off”. For DHT to work, a session directory must be defined.
#
# dht = auto

# UDP port to use for DHT.
#
dht_port = 6881

# Enable peer exchange (for torrents not marked private)
#
peer_exchange = yes

#
# Do not modify the following parameters unless you know what you’re doing.
#

# Hash read-ahead controls how many MB to request the kernel to read
# ahead. If the value is too low the disk may not be fully utilized,
# while if too high the kernel might not be able to keep the read
# pages in memory thus end up trashing.
#hash_read_ahead = 10

# Interval between attempts to check the hash, in milliseconds.
#hash_interval = 100

# Number of attempts to check the hash while using the mincore status,
# before forcing. Overworked systems might need lower values to get a
# decent hash checking rate.
#hash_max_tries = 10

# THIS IS BEING USED TO CONNECT WITH RUTORRENT
scgi_port = 127.0.0.1:5000

Во всех адресах вида /home/example/ меняем на /home/ЮЗЕРвашегоСайта/

А также в .rtorrent.rc не забываем сменить:

# For trafic plugin
schedule = trafic,10,00:15:00,”execute = {sh,-c,/usr/bin/php /home/example/public_html/rutorrent/php/initplugins.php example &}”
# For scheduler plugin
schedule = scheduler,10,00:15:00,”execute = {sh,-c,/usr/bin/php /home/examle/public_html/rutorrent/php/initplugins.php example &}”

Меняем везде example имя на пользователя/сайта, который создал virtualmin для вашего сайта.
Чтобы работала простейшая идентификация сделаем следующие подготовительные шаги – отредактируем файл настроек вашего сайта, использовав следующий код, в очередной раз заменив example.ru на ваш домен.conf:

$ sudo nano /etc/apache2/sites-available/example.ru.conf

После строчек

<Directory /home/example/public_html>
……………….
……………….
……………….
</Directory>

Допишем следующее, изменив example на свое

<Directory /home/example/public_html/rutorrent>
AllowOverride AuthConfig
Order allow,deny
allow from all
</Directory>

добавим простейшую идентификацию. Создадим файл

$ nano /home/example/public_html/rutorrent/.htaccess

Со следующим содержанием:

AuthName “Need auth”
AuthType Basic
AuthUserFile /home/example/public_html/rutorrent/.htpasswd
require valid-user

Далее создаем .htpasswd:

$ nano /home/example/public_html/rutorrent/.htpasswd

Генерируем логин и пароль с помощью  этого сервиса. Указываем в качестве логина любое понравившеяся имя. Например, “admin”. Получившийся .htpasswd:

admin:$apr1$E44h.Q1S$k0m/9eqoT/RkFjy6xye4g.

и вставляем получившееся содержимое в .htpasswd.
Для корректной работы создадим папки для “admin” (Смотря какой логин вы написали)

$ mkdir /home/example/public_html/rutorrent/share/users/admin/settings
$ mkdir /home/example/public_html/rutorrent/share/users/admin/torrents

Установим права доступа

$ sudo chown -R www-data:www-data /home/example/public_html/rutorrent
$ sudo chmod -R 777 /home/example/public_html/rutorrent

А теперь запустим rtorrent в качестве демона.

Если у вас не стоит пакет screen, то поставим его

$ sudo apt-get install screen

Скачиваем скрипт:

$ wget http://libtorrent.rakshasa.no/attachment/wiki/RTorrentCommonTasks/rtorrentInit.sh?format=raw -O /etc/init.d/rtorrent

Изменим переменню user  в скрипте, на example (соответственно user вашего сайта):

$ sudo nano /etc/init.d/rtorrent

А теперь сам демон:

chmod +x /etc/init.d/rtorrent
update-rc.d rtorrent defaults
/etc/init.d/rtorrent start

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

http://example.ru/rutorrent

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

  1. irmpow
    April 10th, 2012 at 14:26 | #1

    И еще не корректно отображается соотношение скачано/отдано при достижении этого параметра равным 2. Поэтому для идеального варианта все же рекомендую собирать сам rtorrent, xmlrpc-c из исходников/

  1. No trackbacks yet.