Настройка домашнего сервера Linux (Часть 11)

Rtorrent

Для установки запустить:

ipkg install rtorrent
Создать его рабочие директории:

 mkdir -p /opt/torrents/dl
 mkdir -p /opt/torrents/downloaded
 mkdir -p /opt/torrents/session
Так же нужно установить утилиту добавления пользователей:

ipkg install adduser

Далее создаем домашнюю директорию и пользователя под которым будет работать rtorrent:

mkdir -p /opt/home/p2p
adduser --home /opt/home/p2p p2p
Пароль - ввести на усмотрение, он в дальнейшем не понадобится. Даем права вновь созданному пользователю:

chown p2p /opt/home/p2p
chown p2p /opt/torrents/dl
chown p2p /opt/torrents/downloaded
chown p2p /opt/torrents/session
chmod a+r /opt/etc/rtorrent.conf
chmod a+x /opt/bin/rtorrent
Создаем файл запуска rtorrent:

vi /opt/etc/init.d/S99rtorrent
Содержимое:

#!/bin/sh

user="p2p"
config="/opt/etc/rtorrent.conf"
options="-n -o import=/opt/etc/rtorrent.conf"
base="/opt/share/torrent"
srnname="rtorrent"
logfile="/opt/var/log/rtorrentInit.log"

PATH=/opt/bin:/opt/sbin:/usr/bin:/sbin:/bin:/usr/sbin
DESC="rtorrent"
NAME=rtorrent
DAEMON=$NAME
SCRIPTNAME=/etc/init.d/$NAME

# Do not proceed unless some apps are available.
test -x /opt/bin/screen || ( echo "screen not found." | tee -a "$logfile" >&2 ; exit 2 )
test -x /opt/bin/su -o -x /bin/su || ( echo "su not found." | tee -a "$logfile" >&2 ; exit 2 )

checkcnfg() {
	exists=0
	for i in `echo "$PATH" | tr ':' '\n'` ; do
		if [ -f $i/$NAME ] ; then
			exists=1
			break
		fi
	done
	if [ $exists -eq 0 ] ; then
		echo "cannot find rtorrent binary in PATH $PATH" | tee -a "$logfile" >&2
		exit 3
	fi
	if ! [ -r "${config}" ] ; then 
		echo "cannot find readable config ${config}. check that it is there and permissions are appropriate" | tee -a "$logfile" >&2
		exit 3 
	fi 
	session=`getsession "$config"` 
	if ! [ -d "${session}" ] ; then
		echo "cannot find readable session directory ${session} from config ${config}. check permissions" | tee -a "$logfile" >&2
		exit 3
	fi
}

d_start() {
  [ -d "${base}" ] && cd "${base}"
  stty stop undef && stty start undef
  su -c "screen -ls | grep -sq "\.${srnname}[[:space:]]" " ${user} || su -c "screen -dm -S ${srnname} 2>&1 1>/dev/null" ${user} | tee -a "$logfile" >&2
  # this works for the screen command, but starting rtorrent below adopts screen session gid
  # even if it is not the screen session we started (e.g. running under an undesirable gid
  su -c "screen -S "${srnname}" -X screen rtorrent ${options} 2>&1 1>/dev/null" ${user} | tee -a "$logfile" >&2
}

d_stop() {
	session=`getsession "$config"`
	if ! [ -s ${session}/rtorrent.lock ] ; then
		return
	fi
	pid=`cat ${session}/rtorrent.lock | awk -F: '{print($2)}' | sed "s/[^0-9]//g"`
	if ps -A | grep -sq ${pid}.*rtorrent ; then # make sure the pid doesn't belong to another process
		kill -s INT ${pid}
	fi
}

getsession() { 
	session=`awk '/^[[:space:]]*session[[:space:]]*=[[:space:]]*/{print($3)}' "$config"`
	echo $session
}

checkcnfg

case "$1" in
  start)
	echo -n "Starting $DESC: $NAME"
	d_start
	echo "."
	;;
  stop)
	echo -n "Stopping $DESC: $NAME"
	d_stop
	echo "."
	;;
  restart|force-reload)
	echo -n "Restarting $DESC: $NAME"
	d_stop
	sleep 1
	d_start
	echo "."
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
При выполнении данного скрипта потребуются следующие пакеты: procps, grep, gawk и screen. Для их установки выполняем:

 ipkg install procps
 ipkg install grep
 ipkg install screen
 ipkg install gawk
В файл /opt/etc/profile добавить строчки для удобной работы в консоли rtorrent:

alias rt='su -c "screen -r" p2p'
chmod a+rw `tty`
stty start undef
stty stop undef
После изменения сохраняемся

flashfs save && flashfs commit && flashfs enable
Проверяем результаты. Для начала убедиться, что пользователь завелся, и rtorrent под ним работает. Так:

su p2p
 /opt/bin/rtorrent -n -o import=/opt/etc/rtorrent.conf
Теперь нужно завершить ssh сессию. Это необходимо, чтобы написанное в файле profile вступило в действие.
9) Залогиниться снова. На всякий случай - mc не запускать!
Последовательно сказать

 /opt/etc/init.d/S99rtorrent start
 rt
Если консоль появилась - нажать:

ctrl + A  ctrl + D
Готово. Удалось отсоединится от консоли, но rtorrent продолжает работать. Убедиться, что в файле /usr/tmp/local/.files есть следующие строчки:

/etc/passwd
/etc/group
При необходимости отредактировать выполнить.

 flashfs save && flashfs commit && flashfs enable
Если этого не сделать (или, например, если в /usr/tmp/local/.files будут отсутствовать строчки /etc/passwd и /etc/group) то только что заведенный пользователь при перезагрузке исчезнет. Не забыть отредактировать файл конфигурации rtorrent под себя:

vi /opt/etc/rtorrent.conf
Так же нужно добавить следующую строчку в конфиг:

system.method.set_key = event.download.erased,rm_complete,"execute=rm,-rf,--,$d.get_base_path="
Она позволяет удалять загруженные файлы если из интерфейса удален торент.

Пример конфигурационного файла:

# 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.

# Minumum amount of peers to connect per torrent, if available.
#min_peers = 20

# Minumum amount of peers to connect per torrent.
max_peers = 40

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

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

# Global download rate in KiB. "0" for unlimited.
download_rate = 150

# Global upload rate in KiB. "0" for unlimited.
upload_rate = 30

# Downloads
#00:00
schedule = throttle_1,00:00:00,24:00:00,download_rate=0
#06:40
schedule = throttle_2,06:40:00,24:00:00,download_rate=150
#08:00
schedule = throttle_3,08:00:00,24:00:00,download_rate=0
#10:00
schedule = throttle_4,10:00:00,24:00:00,download_rate=150

# Uploads
#00:00                                                                      
schedule = throttle_5,00:00:00,24:00:00,upload_rate=0                     
#06:40                                                                          
schedule = throttle_6,06:40:00,24:00:00,upload_rate=30                       
#08:00                                                                          
schedule = throttle_7,08:00:00,24:00:00,upload_rate=0                         
#10:00                                                                          
schedule = throttle_8,10:00:00,24:00:00,upload_rate=30

# Default directory to save downloaded files. Note it doesn't support
# space yet.
directory = /opt/torrents/downloaded/

# Watch a directory for new torrents, and stop those that have been deleted.
schedule = watch_directory,5,5,load_start=/opt/torrents/dl/*.torrent
system.method.set_key = event.download.erased,rm_complete,"execute=rm,-rf,--,$d.get_base_path="

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

# Default session directory. Make sure you don't run multiple instance
# of rtorrent using the same session directory. Perhaps using a
# relative path?
session = /opt/torrents/session

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

# The ip address the listening socket and outgoing connections is
# bound to.

#bind = rakshasa

# Port range to use for listening.
port_range = 51777-51780

# 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 = ip_tick,0,1800,ip=rakshasa
#schedule = bind_tick,0,1800,bind=rakshasa

#
# 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

# Max number of files to keep open simultaniously.
#max_open_files = 128

# Number of sockets to simultaneously keep open.
#max_open_sockets = <no default>


# Example of scheduling commands: Switch between two ip's every 5
# seconds.

#schedule = "ip_tick1,5,10,ip=torretta"
#schedule = "ip_tick2,10,10,ip=lampedusa"

# Remove a scheduled event.
#schedule_remove = "ip_tick1"

# Stop torrents when reaching upload ratio in percent,
# when also reaching total upload in bytes, or when
# reaching final upload ratio in percent.
# example: stop at ratio 2.0 with at least 200 MB uploaded, or else ratio 20.0
#schedule = ratio,60,60,"stop_on_ratio=200,200M,2000"
#schedule = ratio,30,60,stop_on_ratio=200

# 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 =no 

#
# Do not modify the following parameters unless you know what you're doing.
#
Осталось открыть порты для обмена трафиком, для этого редактируем файл:

vi /usr/local/sbin/post-firewall
Исходя из текущего конфига нужно открыть порты с 51777 по 51780 и 6881, добавляем в файл следующие стоки:

#!/bin/sh
iptables -I INPUT -p tcp --dport 51777:51780 -j ACCEPT
iptables -I INPUT -p tcp --dport 6881 -j ACCEPT
Теперь можно перезагрузиться:

 flashfs save && flashfs commit && flashfs enable && reboot
Прочли: 3153 | Изменено: 31 августа 2011 | Добавлено: 25 апреля 2011 | На главную