Установка оборудования Digium
Для успешной установки карты Digium в Ваш сервер, необходимо внимательно следовать нижеперечисленным инструкциям. В противном случае, оборудование может функционировать неправильно или полностью выйти из строя.
Пошаговая инструкция:
- Выключите компьютер
- Выключите шнур питания из сети 220 вольт.
- Вставьте TDM400P в PCI слот с напряжением 3.3 вольта или 5 вольт. Требуется PCI версии 2.2 или выше.
- Вставьте 4-х пиновый 12-ти вольтный коннектор (такой как кабель питания жесткого диска) белую пластиковую розетку, расположенную в задней части карты.
- Включите сервер.
После включения компьютера нужно выполнить команду lspci, которая выведет на экран краткий список PCI устройств, установленных в компьютере. Фактом нормальной установки оборудования Digium будет наличие строки типа:
03:03.0 Network controller: Tiger Jet Network Inc. Tiger3XX Modem/ISDN interface
Сразу надо обратить внимание на используемые прерывания (IRQ):
cat /proc/interrupts CPU0 CPU1 CPU2 CPU3 0: 13823496 0 0 743 IO-APIC-edge timer 1: 25 0 0 3 IO-APIC-edge i8042 7: 0 0 0 0 IO-APIC-edge parport0 9: 0 0 0 0 IO-APIC-level acpi 12: 302 0 0 5 IO-APIC-edge i8042 15: 2 0 0 23 IO-APIC-edge ide1 16: 64862 0 0 1 IO-APIC-level eth0 18: 80313 0 0 21 IO-APIC-level libata 19: 55290127 0 0 1 IO-APIC-level t1xxp NMI: 0 0 0 0 LOC: 13824063 13825626 13825640 13825639 ERR: 0 MIS: 0
|
Для устройства Digum необходимо собственное отдельное прерывание, так как разделяемые прерывания не поддерживаются. Если не хватает свободных прерываний, нужно в BIOS отключить USB, COM, LPT, Audo или NIC. В разделе "Настройка оборудования" будет описано, как убедиться в наличии прерываний в нужном количестве.
Выбор и установка дистрибутива Linux
Linux - это не операционная система, это ядро. В совокупности с системными и прикладными программами ядро образует операционную систему. Для работы Asterisk необходимо ядро ветви 2.4 или 2.6. Существует целый ряд дистрибутивов Linux, в том числе и отечественных (AltLinux, ASPLinux, русские локализации Ubuntu, Gentoo и пр). Обычно системный администратор сам выбирает дистрибутив по своему усмотрению. Мы рекмоендуем Gentoo Linux (http://www.gentoo.ru), так как в данном дистрибутиве заложены лучшие идеи из мира BSD и Linux. Однако Gentoo Linux не рассчитан на новичков и не имеет красивого и простого графического инсталятора. Для начинающих пользователей Linux лучше всего выбирать AltLinux или ASPLinux, так как процесс установки данных дистрибутивов проще и быстрее, чем процесс установки Windows XP.
В целом абсолютно не важно, какой дистрибутив используется, главное, чтобы он был относительно "свежим", т.е. содержал новые версии системных библиотек, используемых Asterisk. Также следует быть очень внимательным с дистрибутивами Fedora Core, так как по умолчанию они включают политики безопасности SeLinux, которые могут мешать нормальной работе Asterisk.
Asterisk предназначен для работы на стандратном ядре Linux, и доп. патчи от сторонних разработчиков могут оказывать существенное влияние на работу Asterisk.
Общая процедура установки Линукс следующая:
- Настроить сервер на загрузку с CD диска. Загрузиться с загрузочного диска с выбранным дистрибутивом. Обычно это диск номер 1 (многие дистрибутивы занимают 2,4 и более CD дисков).
- Выбрать часовой пояс (страну и город), язык, пароль супер администратора root, разделы на жестом диске и др.
- Выбрать нужные пакеты. Новичкам лучше выбрать типичную установку (Server, Workstation). Выполнить установку.
- Выбрать загрузчик (lilo/grub). Некоторые дистрибутивы пропускают этот шаг и устанавливают загрузчик по умолчанию.
- Перегрузить сервер, вытащить CD, настроить загрузку только с жесткого диска, загрузить сервер. Признаком удачной установки является приглашение Login.
Системе Asterisk необходимо следующее доп. программное обеспечение:
- Полные исходные тексты ядра линукс
- Заголовочные файлы библиотеки zlib
- Библиотеки и заголовочные файлы OpenSSL
- Bison 1.875
- Модуль ядра crc_ccitt
Для систем на базе RedHat, а также для других RPMS-основанных систем, это пакеты:
- kernel-devel
- zlib
- zlib-devel
- openssl
- openssl-devel
Данные пакеты можно скачать с сервера http://rpmfind.net или http://rpmseek.com и установить при помощи комманды rpm. Также можно использовать менеджер пакетов yum для установки.
После установки Linux необходимо принять меры по повышению безопасности системы, а именно отключить ненужные сетевые сервисы и процессы, изменить стандрартный порт службы удаленного доступа SSH, настроить правила firewall. Первым делом нужно выяснить, какие сетевые службы активны в данный момент.
Это делается при помощи комманды:
explorer max # netstat -atnup Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:2000 0.0.0.0:* LISTEN 12240/asterisk tcp 0 0 0.0.0.0:6000 0.0.0.0:* LISTEN 9140/X tcp 0 0 0.0.0.0:30022 0.0.0.0:* LISTEN 8961/sshd tcp 0 0 192.168.88.1:57139 192.168.88.2:30022 ESTABLISHED 12023/ssh udp 0 0 0.0.0.0:2727 0.0.0.0:* 12240/asterisk udp 0 0 0.0.0.0:4520 0.0.0.0:* 12240/asterisk udp 0 0 0.0.0.0:5060 0.0.0.0:* 12240/asterisk udp 0 0 0.0.0.0:4569 0.0.0.0:* 12240/asterisk
|
В вышеприведенном примере всего 3 сетевые службы (asterisk, sshd, и X server) находятся в состоянии LISTEN (слушающий сокет). В RPM-основанных дистрибутивах надо использовать комманды ntsysv или chkconfig для выключения ненужных служб.
Файл настройки службы удаленного доступа SSH sshd_config находится в папке /etc/ssh. Надо запустить редактор mcedit /etc/ssh/sshd_config, и изменить (раскоментировать) директиву Port 22. Например, установите Port 33022. Служба SSH - это ворота в вашу систему. Безусловно, эти ворота обладают отличным замком, который пропустит только хозяина. Однако зачем кому-либо вообще знать, что у вашей крепости есть ворота? Именно для этого всегда нужно менять порт службы SSH со значения по умолчанию 22 на что-либо нестандартное.
Если на сервере необходим дополнительный софт, например WEB сервер apache для управления системой Asterisk или бесплатный биллинг A2Billing, желательно ограничить на firewall подключения к данным программам. Для этого используется команда iptables:
explorer max # iptables -I INPUT -p tcp --dport 80 -s \! 192.168.0.0/24 -j DROP explorer max # iptables -vnL Chain INPUT (policy ACCEPT 38M packets, 10G bytes) pkts bytes target prot opt in out source destination 0 0 DROP tcp -- * * !192.168.0.0/24 0.0.0.0/0 tcp dpt:80
Chain FORWARD (policy ACCEPT 555K packets, 146M bytes) pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 69M packets, 13G bytes) pkts bytes target prot opt in out source destination
|
Данное правило игнорирует все запросы на соединения на порт 80 TCP (WEB) от всех хостов, кроме принадлежащих сети 192.168.0.0/24. После изменения правил firewall нужно сохранить данные настройки при помощи комманды:
explorer max # /etc/init.d/iptables save * Saving iptables state ... [ ok ] explorer max #
|
За дополнительной информацией по комманде iptables обращайтесь в системную библиотеку (man iptables).
Установка libpri, zaptel, asterisk
Мы рекомендуем использовать новые стабильные ветви Asterisk. На момент написания данной статьи это ветвь 1.2. Последняя стабильная версия Asterisk - 1.2.9.1. Скачать Asterisk стабильной версии можно с сайта Digium (ftp://ftp.digium.com/pub/). Помимо Asterisk необходимы библиотеки libpri и zaptel, обеспечивающие драйвера для оборудования Digium.
Скачать:
# cd /usr/src # wget http://ftp.digium.com/pub/zaptel/zaptel-1.2-current.tar.gz # wget http://ftp.digium.com/pub/libpri/libpri-1.2-current.tar.gz # wget http://ftp.digium.com/pub/asterisk/asterisk-1.2-current.tar.gz # tar zxvf *current.tar.gz ./
|
Данные комманды скачают Asterisk и нужные библиотеки и распакуют их в директории /usr/src.
Компиляция, сборка и установка:
# cd zaptel-1.2 # make install # cd ../libpri-1.2 # make install # cd ../asterisk-1.2 # make install
|
Для получения образцов файлов конфигурации необходимо также выполнить:
Данная команда установит образцы файлов конфигурации. На этом этапе система Asterisk установлена и готова к использованию. Далее необходимо настроить оборудование Digium.
Настройка оборудования Digium и проблемы эхоподавления
Первым делом необходимо загрузить соотв. драйвер zaptel.
Список:
TE110P => wcte11xp TE205P/TE207P/TE210P/TE212P => wct2xxp TE405P/TE407P/TE410P/TE412P => wct4xxp TDM400P => wctdm TDM2400P => wctdm24xxp
|
Пример загруженного драйвера карты TE110P:
pbx2 ~ # lsmod Module Size Used by ip_vs_rr 2560 1 wct1xxp 15648 0 zaptel 187524 51 wct1xxp
|
Настройки параметров соединения осуществляется в файлах конфигурации /etc/zaptel.conf и /etc/asterisk/zapata.conf.
Пример работающих файлов для карты TE110P:
cat /etc/zaptel.conf
span=1,0,0,esf,b8zs,yellow bchan=1-23 dchan=24 loadzone = us defaultzone=us
cat /etc/asterisk/zapata.conf [channels] language => en rxwink => 300 usecallerid => yes hidecallerid => no callwaiting => yes usecallingpres => yes callwaitingcallerid => yes threewaycalling => yes transfer => yes cancallforward => yes callreturn => yes callgroup => 1 pickupgroup => 1 echocancel => yes echocancelwhenbridged => yes echotraining => yes relaxdtmf => yes rxgain => 0 txgain => 0 immediate => no faxdetect => both signalling => pri_cpe switchtype => dms100 callerid => asreceived context => from-zap group => 1 channel => 1-23
|
Настройка SIP/AX2 подключений и плана набора номера
В качестве примера приведем настройки SIP телефона, подключенного к Asterisk, и плана набора, позволяющего принимать звонки из города и звонить на городские телефоны через карту TE110P (1E1). Примеры настройки другого оборудования в соотв. документах.
В файл sip.conf надо добавить секцию:
[sipura_1] type=friend host=dynamic nat=yes secret=Hjd7lo92Ba context=from-sip
|
План набора номера конфигурируется в файле extensions.conf:
[from_sip] exten => _XXXXXXX,1,Set(CALLERID(num)=2323956) exten => _XXXXXXX,n,Dial(ZAP/r1/${EXTEN},60,tT) exten => _XXXXXXX,n,Congestion exten => _XXXXXXX,n,Hangup exten => t,1,Hangup exten => i,1,Hangup exten => s,1,Hangup
[from-zap] exten => 2323956,1,Dial(SIP/${EXTEN}@sipura_1,60,Tt) exten => 2323956,n,Hangup
|
Пояснения:
- Обычно провайдеры телефонной связи выделяют клиенту номерную емкость, и все звонки от клиента должны иметь номер абонента А (звонящий) из выделенного диапазона. Для этого надо использовать функцию Asterisk CALLERID.
- r1 в строке с командой Dial означает алгоритм перебора b-каналов в потоке. Остальные варианты: g r G R
- Служебные екстены t,i,s означают timeout, invalid, start. В нашем примере, если в течение 60 секунд нет ответа абонента, сработает команда Hangup. Если SIP клиент наберет номер менее или более 7 цифр, сработает екстен i (invalid ) и завершение вызова. Если SIP клиент не пришлет номера вообще, также произойдет завершение сеанса связи.
Проверка установки Asterisk
Для начала нужно запустить Asterisk без отрыва от управляющей консоли при помощи команды asterisk -vvvvvgnc.
Самое главное в конце получить:
Если все ок, пора переводить asterisk в демон-процесс:
explorer*CLI> stop now explorer*CLI> Disconnected from Asterisk server max@explorer ~ $ max@explorer ~ $ safe_asterisk max@explorer ~ $ Asterisk ended with exit status 0 Asterisk shutdown normally. max@explorer ~ $
|
Данная команда запускает Asterisk, а также процесс, который перезапустит Asterisk в случае случайного падения.
Теперь подключимся к работающему процессу Asterisk (флаг -r):
max@explorer ~ $ asterisk -vvvncr == Parsing '/home/max/ASTERISK/asterisk-1.2.1//etc/asterisk/asterisk.conf': Found == Parsing '/home/max/ASTERISK/asterisk-1.2.1//etc/asterisk/extconfig.conf': Found == Binding iaxusers to mysql/pbx_manager_new/peer == Binding iaxpeers to mysql/pbx_manager_new/peer == Binding sipusers to mysql/pbx_manager_new/peer == Binding sippeers to mysql/pbx_manager_new/peer == Binding voicemail to mysql/pbx_manager_new/voicemail Asterisk 1.2.1, Copyright (C) 1999 - 2005 Digium. Written by Mark Spencer <markster@digium.com> ========================================================================= Connected to Asterisk 1.2.1 currently running on explorer (pid = 13255) Verbosity was 0 and is now 3 explorer*CLI>
|
Можно по команде help получить список возможных действий:
explorer*CLI> help ! Execute a shell command abort halt Cancel a running halt add extension Add new extension into context add ignorepat Add new ignore pattern add queue member Add a channel to a specified queue ael debug contexts Enable AEL contexts debug ael debug macros Enable AEL macros debug ael debug read Enable AEL read debug ael debug tokens Enable AEL tokens debug ael no debug Disable AEL debug messages ael reload Reload AEL configuration agent logoff Sets an agent offline agi debug Enable AGI debugging agi no debug Disable AGI debugging answer Answer an incoming console call autoanswer Sets/displays autoanswer cdr mysql status Show connection status of cdr_mysql cdr status Display the CDR status console Sets/displays active console database del Removes database key/value database deltree Removes database keytree/values database get Gets database value database put Adds/updates database value database show Shows database contents database showkey Shows database contents debug channel Enable debugging on a channel debug level Set global debug level dial Dial an extension on the console dnsmgr reload Reloads the DNS manager configuration dnsmgr status Display the DNS manager status dont include Remove a specified include from context dump agihtml Dumps a list of agi command in html format dundi debug Enable DUNDi debugging dundi flush Flush DUNDi cache dundi lookup Lookup a number in DUNDi dundi no debug Disable DUNDi debugging dundi no store history Disable DUNDi historic records dundi precache Precache a number in DUNDi dundi query Query a DUNDi EID dundi show entityid Display Global Entity ID dundi show mappings Show DUNDi mappings dundi show peers Show defined DUNDi peers dundi show peer Show info on a specific DUNDi peer dundi show precache Show DUNDi precache dundi show requests Show DUNDi requests dundi show trans Show active DUNDi transactions dundi store history Enable DUNDi historic records extensions reload Reload extensions and *only* extensions feature show channels Show status of feature channels flash Flash a call on the console group show channels Show active channels with group(s) hangup Hangup a call on the console help Display help list, or specific help on a command iax2 debug Enable IAX debugging iax2 jb debug Enable IAX jitterbuffer debugging iax2 no debug Disable IAX debugging iax2 no jb debug Disable IAX jitterbuffer debugging iax2 no trunk debug Disable IAX trunk debugging iax2 provision Provision an IAX device iax2 prune realtime Prune a cached realtime lookup iax2 reload Reload IAX configuration iax2 set jitter Sets IAX jitter buffer iax2 show cache Display IAX cached dialplan iax2 show channels Show active IAX channels iax2 show firmware Show available IAX firmwares iax2 show netstats Show active IAX channel netstats iax2 show peer Show details on specific IAX peer iax2 show peers Show defined IAX peers iax2 show provisioning Show iax provisioning iax2 show registry Show IAX registration status iax2 show stats Display IAX statistics iax2 show users Show defined IAX users iax2 test losspct Set IAX2 incoming frame loss percentage iax2 trunk debug Enable IAX trunk debugging include context Include context in other context indication add Add the given indication to the country indication remove Remove the given indication from the country init keys Initialize RSA key passcodes load Load a dynamic module by name local show channels Show status of local channels logger reload Reopens the log files logger rotate Rotates and reopens the log files logger show channels List configured log channels mgcp audit endpoint Audit specified MGCP endpoint mgcp debug Enable MGCP debugging mgcp no debug Disable MGCP debugging mgcp reload Reload MGCP configuration mgcp show endpoints Show defined MGCP endpoints mixmonitor Execute a MixMonitor command moh classes show List MOH classes moh files show List MOH file-based classes moh reload Music On Hold mute Disable mic input no debug channel Disable debugging on a channel odbc connect Connect to ODBC DSN odbc disconnect Disconnect from ODBC DSN odbc show Show ODBC DSN(s) realtime load Used to print out RealTime variables. realtime mysql status Shows connection information for the MySQL RealTime driver realtime update Used to update RealTime variables. reload Reload configuration remove extension Remove a specified extension remove ignorepat Remove ignore pattern from context remove queue member Removes a channel from a specified queue restart gracefully Restart Asterisk gracefully restart now Restart Asterisk immediately restart when convenient Restart Asterisk at empty call volume rtp debug Enable RTP debugging rtp debug ip Enable RTP debugging on IP rtp no debug Disable RTP debugging save dialplan Save dialplan send text Send text to the remote device set debug Set level of debug chattiness set verbose Set level of verboseness show agents Show status of agents show agi Show AGI commands or specific help show applications Shows registered dialplan applications show application Describe a specific dialplan application show audio codecs Shows audio codecs show channel Display information on a specific channel show channels Display information on channels show channeltypes Show available channel types show codecs Shows codecs show codec Shows a specific codec show config mappings Show Config mappings (file names to config engines) show dialplan Show dialplan show features Lists configured features show file formats Displays file formats show functions Shows registered dialplan functions show function Describe a specific dialplan function show hints Show dialplan hints show image codecs Shows image codecs show image formats Displays image formats show indications Show a list of all country/indications show keys Displays RSA key information show manager command Show a manager interface command show manager commands List manager interface commands show manager connected Show connected manager interface users show modules List modules and info show modules like List modules and info show parkedcalls Lists parked calls show queue Show status of a specified queue show queues Show status of queues show switches Show alternative switches show translation Display translation matrix show uptime Show uptime information show version Display version info show version files Show versions of files used to build Asterisk show video codecs Shows video codecs show voicemail users List defined voicemail boxes show voicemail zones List zone message formats sip debug Enable SIP debugging sip debug ip Enable SIP debugging on IP sip debug peer Enable SIP debugging on Peername sip history Enable SIP history sip no debug Disable SIP debugging sip no history Disable SIP history sip notify Send a notify packet to a SIP peer sip prune realtime Prune cached Realtime object(s) sip prune realtime peer Prune cached Realtime peer(s) sip prune realtime user Prune cached Realtime user(s) sip reload Reload SIP configuration sip show channels Show active SIP channels sip show channel Show detailed SIP channel info sip show domains List our local SIP domains. sip show history Show SIP dialog history sip show inuse List all inuse/limits sip show objects Show all SIP object allocations sip show peer Show details on specific SIP peer sip show peers Show defined SIP peers sip show registry Show SIP registration status sip show settings Show SIP global settings sip show subscriptions Show active SIP subscriptions sip show users Show defined SIP users sip show user Show details on specific SIP user skinny debug Enable Skinny debugging skinny no debug Disable Skinny debugging skinny show devices Show defined Skinny devices skinny show lines Show defined Skinny lines per device soft hangup Request a hangup on a given channel stop gracefully Gracefully shut down Asterisk stop now Shut down Asterisk immediately stop when convenient Shut down Asterisk at empty call volume transfer Transfer a call to a different extension unload Unload a dynamic module by name unmute Enable mic input
|
Наиболее часто используемые команды: show channels, sip show peers ,iax2 show peers, show dialplan и др.
Чтобы увидеть ошибки подключения SIP или IAX2 клиентов, нужно включить дебаг соотв. канала.
Пример:
*CLI> sip debug SIP Debugging enabled *CLI> iax2 debug IAX2 Debugging Enabled *CLI> sip no debug SIP Debugging Disabled *CLI> iax2 no debug IAX2 Debugging Disabled *CLI> sip debug ip 1.1.1.1 SIP Debugging Enabled for IP: 1.1.1.1 *CLI> sip no debug SIP Debugging Disabled *CLI>
|