Игорь Олемской — практические заметки по системному администрированию Linux CentOS

Архив тега ‘debian’

Linux UPnP (перепечатка)

Комментариев нет

Для того чтобы клиенты могли прозрачно открывать порты на шлюзе, был разработан набор протоколв Universal Plug and Play (UPnP), например для того чтобы можно было раздавать торренты.

На днях я снял дома старый добрый Linksys WRT54G, теперь раздачей интернета занимается linux-овая машинка. Для раздачи торррентов например, нужно разрешить соединения внутрь сети. Для этого можно пробросить разные порты на разные машины, и в случае добавления клиентов/машин это придется делать вручную. Это не самый удобный спопосб, но можно использовать UPnP который будет сам пробрасывать нужные порты через iptables.

Установка:

sudo apt-get install linux-igd -y

Настраиваем:

cat /etc/default/linux-igd
# External interface name.  If undefined then upnpd will not be started.
EXTIFACE=ppp0
 
# Internal interface name.  If undefined then upnpd will not be started.
INTIFACE=eth0

Добавляем правила в iptables:

iptables -N UPNP
iptables -N UPNP iptables -A FORWARD -j UPNP
 
iptables-save > /etc/iptables.up.rules

Запускаем upnpd

/etc/init.d/linux-igd start

Перезапускаем, например, торрент клиент с включенным UPnP и видим появившиеся правила в iptables:

-A FORWARD -d 192.168.1.106/32 -p tcp -m tcp --dport 51413 -j ACCEPT
-A PREROUTING -i ppp0 -p tcp -m tcp --dport 51413 -j DNAT --to-destination 192.168.1.106:51413

На этом всё.

Директория весом в 1Гб (перепечатка)

Комментариев нет

Вы видели когда нибудь папочку весом 1Gb? Имеется в виду вес не содержимого низлежащих файлов, а вес самой папочки, т.е. листинг имен файлов весом 1Gb… около 13млн инод внутри…

hosted-by:/> stat /var/www/admin/data/mod-tmp
  File: `/var/www/admin/data/mod-tmp'
  Size: 1022976000      Blocks: 1999960    IO Block: 4096   directory
Device: 802h/2050d      Inode: 11403505    Links: 2
Access: (2700/drwx--S---)  Uid: (   33/www-data)   Gid: (  502/   admin)
Access: 2011-05-30 23:44:44.000000000 +0300
Modify: 2011-05-30 08:36:27.000000000 +0300
Change: 2011-05-30 08:36:27.000000000 +0300


При попытке просмотра папочки, ls задумывается минут на 20, а потом выдает:

hosted-by:/> ls -1 /var/www/admin/data/mod-tmp > /tmp/ls
ls: memory exhausted

Поступили жалобы на «некорректную работу сервера». Да я думаю некорректная…

hosted-by:/> df -i
Filesystem            Inodes   IUsed   IFree IUse% Mounted on
/dev/sda2            14884864 14884864       0  100% /

Найти потенциальных пожирателей инод смог по команде

find / -type d -size +100k -print

На этой папочке find заткнулся навечно, что навело на мысль.

Диагноз: рак. Лечение: ампутация.

screen
rm -rf /var/www/admin/data/mod-tmp && mkdir /var/www/admin/data/mod-tmp && chmod 777 /var/www/admin/data/mod-tmp

При скорости удаления около 100 файлов в секунду, а файлов более 10 млн, можно идти спать….

Дальнейшее вскрытие показало что в папочке были файлы сессий php. На Debian Lenny почему то выпиливатель старых файлов сессий выключен по дефолту:

hosted-by:~> grep -B 5 session.gc_probability /etc/php5/apache2/php.ini
 
; This is disabled in the Debian packages, due to the strict permissions
; on /var/lib/php5.  Instead of setting this here, see the cronjob at
; /etc/cron.d/php5, which uses the session.gc_maxlifetime setting below.
; php scripts using their own session.save_path should make sure garbage
; collection is enabled by setting session.gc_probability
;session.gc_probability = 0

Вопиющее распиздяйство. Хотя скорей всего дело в нестандартном расположении session.save_path, который ставит ISP Manager.

installing SHOUTcast streaming server on debian x86_64 (перепечатка)

Комментариев нет

Компания Nullsoft, та что радует виндовых пользователей проигрывателем winamp выпускает еще и стриминг сервер, проще говоря сервер онлайн радио. Ставить будем на debian x86_64

mkdir /opt/sc && cd /opt/sc
wget http://yp.shoutcast.com/downloads/sc1-9-8/sc_serv_1.9.8_Linux.tar.gz
tar zxf sc_serv_1.9.8_Linux.tar.gz
rm -rf sc_serv_1.9.8_Linux.tar.gz README.TXT

Открываем конфиг /opt/sc/sc_serv.conf в любом текстовом редакторе (например vim)
найдите строку Password=changeme и поменяйте changeme на свой пароль
Затем строку ; AdminPassword=adminpass
уберите первый символ точки с запятой и замените adminpass на другой пароль (не должен совпадать с предыдущим), теперь строку ScreenLog=1 и замените на ScreenLog=0 и RealTime=1 на RealTime=0.

установим либы для 64-х разрядной платформы:

apt-get install ia32-libs -y

без них при запуске шоткаста будут ошибки вида

-bash: ./opt/sc/sc_serv: No such file or directory


Запускаем:

/opt/sc/sc_serv /opt/sc/sc_serv.conf >/dev/null 2>&1 &

Проверяем:

netstat -tnlp | grep sc
tcp        0      0 0.0.0.0:8000            0.0.0.0:*               LISTEN      20198/sc_serv
tcp        0      0 0.0.0.0:8001            0.0.0.0:*               LISTEN      20198/sc_serv

Всё нормально, добавим в «автозапуск»:

echo '/opt/sc/sc_serv /opt/sc/sc_serv.conf >/dev/null 2>&1 & ' >> /etc/rc.local

Теперь займеся собственно шарманкой которая будет отдавать mp3 поток шоуткасту. В качестве шарманки будет самый свежий winamp и плагин SHOUTcast DSP

Переходим к настройке, в окне winamp нажмите Ctrl+P и переходим в раздел DSP/Effect. Двойной клие по Nullsoft SHOUTcat Source DSP вкладка Output. Ставим галочку legacy, и autoconnect, заполняем поле с ip адресом сервера shoutcast и пароль который мы задвали.

На этом всё.

Cannot set LC_CTYPE to default locale (перепечатка)

Комментариев нет

Свежий VPS с Debian 5.0 на Virtuozo, в разных местах (например при apt-get install) сыпет ошибками:

locale: Cannot set LC_CTYPE to default locale: No such file or directory
locale: Cannot set LC_MESSAGES to default locale: No such file or directory
locale: Cannot set LC_ALL to default locale: No such file or directory

локаль нужная ru_RU.utf8 т.ч. её и ставим:

localedef ru_RU.UTF-8 -i ru_RU -fUTF-8

Ну мало ли, вдруг ru_RU.CP1251 пригодится, поставим и её:

localedef --no-archive -c -f CP1251 -i ru_RU ru_RU.CP1251

Проверям, проблемы уже нет.

# locale
LANG=ru_RU.utf8
LC_CTYPE="ru_RU.utf8"
LC_NUMERIC="ru_RU.utf8"
LC_TIME="ru_RU.utf8"
LC_COLLATE="ru_RU.utf8"
LC_MONETARY="ru_RU.utf8"
LC_MESSAGES="ru_RU.utf8"
LC_PAPER="ru_RU.utf8"
LC_NAME="ru_RU.utf8"
LC_ADDRESS="ru_RU.utf8"
LC_TELEPHONE="ru_RU.utf8"
LC_MEASUREMENT="ru_RU.utf8"
LC_IDENTIFICATION="ru_RU.utf8"
LC_ALL=

Debian NO_PUBKEY 9AA38DCD55BE302B (перепечатка)

Комментариев нет

На свежесозданном контейнере OpenVZ с debian-minimal при apt-get update вылезла пара ошибок.

Первая:

W: There is no public key available for the following key IDs:
9AA38DCD55BE302B
W: GPG error: http://security.debian.org lenny/updates Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 9AA38DCD55BE302B
W: You may want to run apt-get update to correct these problems

лечим:

root@zabbix:/# gpg --keyserver wwwkeys.eu.pgp.net --recv 9AA38DCD55BE302B
gpg: requesting key 55BE302B from hkp server wwwkeys.eu.pgp.net
gpg: /root/.gnupg/trustdb.gpg: trustdb created
gpg: key 55BE302B: public key "Debian Archive Automatic Signing Key" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)
root@zabbix:/# gpg --export --armor 9AA38DCD55BE302B | apt-key add -
OK

вторая:

W: GPG error: http://volatile.debian.org lenny/volatile Release: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY DFD993306D849617

Лечим:

root@zabbix:/# wget -q http://www.debian.org/volatile/lenny-volatile.asc  -O- | apt-key add - 
OK

openvz for Debian Squeeze (перепечатка)

Комментариев нет

I am still at the OpenVZ booth at LinuxTag 2010 in Berlin. At least two people asked me about the status of OpenVZ kernel for the upcoming Debian Squeeze. Specifically, they said, there is no openvz kernel in «testing» repository (i.e. what will become Squeeze when it will be released). My guess is some more people interesting in that, so here's the public answer.

We are working pretty close with the Debian kernel team, you can see some traces of that on either debian-kernel AT lists.debian.org or debian AT openvz.org mailing lists. Specifically, we work together to bring good quality OpenVZ kernel to Squeeze, and this was one of the main reasons for us to port to 2.6.32.

But yesterday we tried to search for openvz linux-image on packages.debian.org and it gave us no results for testing. I then emailed Max Attems (who maintains our kernels in Debian) and this is his response:

it should be there now, the switch to libata did uphold testing
transition of linux-2.6 for quite some time, so testing had an
outdated linux-2.6 for quite some while

Indeed, the kernel is now there. So yes, Squeeze will have OpenVZ kernel, and I guess it can also be used by people who switched to Ubuntu 10.4.

openvz for Debian Squeeze (перепечатка)

Комментариев нет

I am still at the OpenVZ booth at LinuxTag 2010 in Berlin. At least two people asked me about the status of OpenVZ kernel for the upcoming Debian Squeeze. Specifically, they said, there is no openvz kernel in «testing» repository (i.e. what will become Squeeze when it will be released). My guess is some more people interesting in that, so here's the public answer.

We are working pretty close with the Debian kernel team, you can see some traces of that on either debian-kernel AT lists.debian.org or debian AT openvz.org mailing lists. Specifically, we work together to bring good quality OpenVZ kernel to Squeeze, and this was one of the main reasons for us to port to 2.6.32.

But yesterday we tried to search for openvz linux-image on packages.debian.org and it gave us no results for testing. I then emailed Max Attems (who maintains our kernels in Debian) and this is his response:

it should be there now, the switch to libata did uphold testing
transition of linux-2.6 for quite some time, so testing had an
outdated linux-2.6 for quite some while

Indeed, the kernel is now there. So yes, Squeeze will have OpenVZ kernel, and I guess it can also be used by people who switched to Ubuntu 10.4.

12.06.2010

debian: ошибка при сборке apache 1.3.41 (перепечатка)

Комментариев нет

При сборке apache 1.3.41 под debian 5.0 lenny возникает ошибка: отсутствует ndbm.h:

$ ./configure \
  --prefix=/usr/local/apache \
  --enable-module=most \
  --enable-shared=max \
$ make
...
mod_auth_dbm.c:42:18: error: ndbm.h: No such file or directory
mod_auth_dbm.c: In function ‘get_dbm_pw’:
mod_auth_dbm.c:110: error: ‘DBM’ undeclared (first use in this function)
mod_auth_dbm.c:110: error: (Each undeclared identifier is reported only once
mod_auth_dbm.c:110: error: for each function it appears in.)
mod_auth_dbm.c:110: error: ‘f’ undeclared (first use in this function)
mod_auth_dbm.c:111: error: ‘datum’ undeclared (first use in this function)
mod_auth_dbm.c:111: error: expected ‘;’ before ‘d’
mod_auth_dbm.c:114: error: ‘q’ undeclared (first use in this function)
mod_auth_dbm.c:128: error: ‘d’ undeclared (first use in this function)
make[4]: *** [mod_auth_dbm.so] Error 1
make[3]: *** [all] Error 1
make[2]: *** [subdirs] Error 1
make[2]: Leaving directory `/usr/src/apache_1.3.41/src'
make[1]: *** [build-std] Error 2
make[1]: Leaving directory `/usr/src/apache_1.3.41'
make: *** [build] Error 2

Поиск по содержимому пакетов показывает, что такого файла в пакетах debian нет. Пишут, что раньше он входил в состав libc6. В одном из листов рассылки было найдено такое решение:

$ sudo apt-get install libgdbm-dev
$ ln -s /usr/include/gdbm-ndbm.h /usr/include/ndbm.h

Что интересно, работает.

debian: добавляем в iptables поддержку ip sets (ipset) (перепечатка)

Комментариев нет

IP Sets – расширение пакетного фильтра ядра iptables, которое позволяет комфортно работать с большими наборами адресов/сетей. При написании правил iptables при этом мы оперируем именованными списками.

Это, пожалуй, единственный на сегодняшний день доступный способ писать правила для большого количества хостов/сетей, не перечисляя каждый из них в отдельном правиле. Если ваш сайт, работающий под linux, подвергается DDOS, вы наверняка уже знаете про IP Sets. Если нет — http://ipset.netfilter.org/.

Утилита ipset живет в одноименном пакете, а все необходимые патчи ядра входят в состав пакета netfilter-extensions-source, который собирается и устанавливается при помощи утилиты module-assistant (которая для удобства имеет более короткое имя: m-a).

Примерный сценарий установки ip sets выглядит так:

$ sudo apt-get install ipset
$ sudo apt-get install netfilter-extensions-source
$ uname -a
Linux host.domain.tld 2.6.26-1-686 #1 SMP Fri Mar 13 18:08:45 UTC 2009 i686 GNU/Linux
# версия пакета linux-headers должна совпадать с версией ядра, для которого собирается netfilter-extensions
$ sudo apt-get install linux-headers-2.6.26-1-686
$ sudo m-a build netfilter-extensions
$ sudo m-a update && m-a a-i netfilter-extensions

Версия пакета заголовков ядра должна точно соответствовать версии активного ядра, для которого собирается ipset.

firefox: оптимизация внутренних баз данных sqlite (перепечатка)

Комментариев нет

$ find .mozilla/firefox -type f -name "*.sqlite" -exec time sqlite3 \{\} "VACUUM" ";"

via