Sistema de facturación para FreeSWTCH: PyFreeBilling en Ubuntu 12.04 LTS

Hoy veremos como instalar el sistema de facturación para FreeSWITCH, PyFreeBilling en Ubuntu 12.04 LTS. Utilizaremos un VPS de DigitalOcean.

Una vez creado el “Droplet”, accedemos vía SSH y como primera cosa actualizamos el sistema:

apt-get update

apt-get upgrade

Cambiamos la hora predefinida:

rm /etc/localtime

ln -s /usr/share/zoneinfo/America/Bogota /etc/localtime

Creamos el área de SWAP:

dd if=/dev/zero of=/swapfile bs=1024 count=524288
524288+0 records in
524288+0 records out
536870912 bytes (537 MB) copied, 2.13628 s, 251 MB/s

Cambiamos los permisos del archivo creado:

chown root:root /swapfile

chmod 0600 /swapfile

Configuramos el área de Swap:

mkswap /swapfile
Setting up swapspace version 1, size = 524284 KiB
no label, UUID=95ea7944-5525-4994-844a-c0e909f701e9

Activamos el área de Swap:

swapon /swapfile

Configuramos para que se active al boot del servidor:

nano /etc/fstab

al final del archivo añadimos:

/swapfile none swap sw 0 0

Guardamos los cambios e instalamos ntp (Network Time Protocol):

apt-get install ntp

Luego reiniciamos el servidor:

reboot

Accedemos nuevamente e instalamos una serie de paquetes para la compilación de FreeSWITCH:

apt-get install git-core build-essential autoconf automake libtool libncurses5 libncurses5-dev gawk libjpeg-dev zlib1g-dev pkg-config libssl-dev libpq-dev unixodbc-dev odbc-postgresql postgresql postgresql-client libpq-dev libxml2-dev libxslt1-dev ntp ntpdate libapache2-mod-wsgi apache2 gcc python-setuptools python-pip libdbd-pg-perl libtext-csv-perl sqlite3 libsqlite3-dev libcurl4-openssl-dev libpcre3-dev libspeex-dev libspeexdsp-dev libldns-dev libedit-dev libmemcached-dev python-psycopg2 python-dev libgeoip-dev

Descargamos, compilamos e instalamos la ultima versión de FreeSWITCH:

cd /usr/src

git clone https://stash.freeswitch.org/scm/fs/freeswitch.git

cd freeswitch
./bootstrap.sh -j

nano modules.conf

descomentamos los siguientes módulos (quitando el carácter # presente a inicio línea):

applications/mod_memcache
applications/mod_nibblebill
codecs/mod_siren
codecs/mod_amrwb

Guardamos los cambios y continuamos con la compilación e instalación:

./configure
make
make install
make cd-sounds-install
make cd-moh-install

Compilamos e instalamos el Event Socket LIbrary para el lenguaje python:

cd libs/esl
make pymod
make pymod-install

Creamos el usuario y el grupo freeswitch de la siguiente forma:

groupadd freeswitch
adduser --disabled-password  --quiet --system --home /usr/local/freeswitch --gecos "FreeSWITCH Voice Platform" --ingroup daemon freeswitch

Cambiamos los permisos en la carpeta de instalación de FreeSWITCH:

chown -R freeswitch:daemon /usr/local/freeswitch/
chmod -R ug=rwX,o= /usr/local/freeswitch/
chmod -R u=rwx,g=rx /usr/local/freeswitch/bin/

Creamos el script de arranque de FreeSWITCH:

nano /etc/init.d/freeswitch

----------------

#!/bin/bash
### BEGIN INIT INFO
# Provides:          freeswitch
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Description:       Freeswitch debian init script.
# Author:            Matthew Williams
#
### END INIT INFO
# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin
DESC="Freeswitch"
NAME=freeswitch
DAEMON=/usr/local/freeswitch/bin/$NAME
DAEMON_ARGS="-nc -nonat"
PIDFILE=/usr/local/freeswitch/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

FS_USER=freeswitch
FS_GROUP=daemon

# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

#
# Function that sets ulimit values for the daemon
#
do_setlimits() {
        ulimit -c unlimited
        ulimit -d unlimited
        ulimit -f unlimited
        ulimit -i unlimited
        ulimit -n 999999
        ulimit -q unlimited
        ulimit -u unlimited
        ulimit -v unlimited
        ulimit -x unlimited
        ulimit -s 240
        ulimit -l unlimited
        return 0
}

#
# Function that starts the daemon/service
#
do_start()
{
    # Set user to run as
        if [ $FS_USER ] ; then
      DAEMON_ARGS="`echo $DAEMON_ARGS` -u $FS_USER"
        fi
    # Set group to run as
        if [ $FS_GROUP ] ; then
          DAEMON_ARGS="`echo $DAEMON_ARGS` -g $FS_GROUP"
        fi

        # Return
        #   0 if daemon has been started
        #   1 if daemon was already running
        #   2 if daemon could not be started
        start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null -- \
                || return 1
        do_setlimits
        start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --background -- \
                $DAEMON_ARGS \
                || return 2
        # Add code here, if necessary, that waits for the process to be ready
        # to handle requests from services started subsequently which depend
        # on this one.  As a last resort, sleep for some time.
}

#
# Function that stops the daemon/service
#
do_stop()
{
        # Return
        #   0 if daemon has been stopped
        #   1 if daemon was already stopped
        #   2 if daemon could not be stopped
        #   other if a failure occurred
        start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
        RETVAL="$?"
        [ "$RETVAL" = 2 ] && return 2
        # Wait for children to finish too if this is a daemon that forks
        # and if the daemon is only ever run from this initscript.
        # If the above conditions are not satisfied then add some other code
        # that waits for the process to drop all resources that could be
        # needed by services started subsequently.  A last resort is to
        # sleep for some time.
        start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
        [ "$?" = 2 ] && return 2
        # Many daemons don't delete their pidfiles when they exit.
        rm -f $PIDFILE
        return "$RETVAL"
}

#
# Function that sends a SIGHUP to the daemon/service
#
do_reload() {
        #
        # If the daemon can reload its configuration without
        # restarting (for example, when it is sent a SIGHUP),
        # then implement that here.
        #
        start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
        return 0
}

case "$1" in
  start)
        [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
        do_start
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
  stop)
        [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
        do_stop
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
  status)
       status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $?
       ;;
  #reload|force-reload)
        #
        # If do_reload() is not implemented then leave this commented out
        # and leave 'force-reload' as an alias for 'restart'.
        #
        #log_daemon_msg "Reloading $DESC" "$NAME"
        #do_reload
        #log_end_msg $?
        #;;
  restart|force-reload)
        #
        # If the "reload" option is implemented then remove the
        # 'force-reload' alias
        #
        log_daemon_msg "Restarting $DESC" "$NAME"
        do_stop
        case "$?" in
          0|1)
                do_start
                case "$?" in
                        0) log_end_msg 0 ;;
                        1) log_end_msg 1 ;; # Old process is still running
                        *) log_end_msg 1 ;; # Failed to start
                esac
                ;;
          *)
                # Failed to stop
                log_end_msg 1
                ;;
        esac
        ;;
  *)
        #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
        echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
        exit 3
        ;;
esac

exit 0

-----------------

Guardamos los cambios y volvemos ejecutable el archivo:

chmod +x /etc/init.d/freeswitch

Lo añadimos a la lista de servicios que se iniciarán al boot del servidor:

update-rc.d freeswitch defaults

Creamos un enlace simbólico a la utilidad para acceder a la consola de FreeSWITCH:

ln -s /usr/local/freeswitch/bin/fs_cli /bin/fscli

accedemos a PostgreSQL donde creamos un nuevo usuario y definimos sus permisos:

sudo -i -u postgres
createuser -P pyfreebilling
Enter password for new role:
Enter it again:
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) y

Creamos la base de datos pyfreebilling:

createdb -O pyfreebilling -E UTF8 pyfreebilling

Salimos de la consola del usuario postgres de PostgreSQL:

exit

Configuramos ODBC para la conexión con PostgreSQL:

mv /etc/odbcinst.ini /etc/odbcinst.ini.old

nano /etc/odbcinst.ini

[PostgreSQL]
Description     = PostgreSQL ODBC driver (Unicode version)
Driver          = /usr/lib/x86_64-linux-gnu/odbc/psqlodbcw.so
Setup           = /usr/lib/x86_64-linux-gnu/odbc/libodbcpsqlS.so
Debug           = 0
CommLog         = 0
UsageCount      = 0
Threading       = 0
MaxLongVarcharSize = 65536

nano /etc/odbc.ini

[freeswitch]
Driver = PostgreSQL
Description = Connection to POSTGRESQL
Servername = 127.0.0.1
Port = 5432
Protocol = 6.4
FetchBufferSize = 99
Username = pyfreebilling
Password = sesamo
Database = pyfreebilling
ReadOnly = no
Debug = 0
CommLog = 0

sesamo es la contraseña que hemos escogido al crear el usuario PostgreSQL pyfreebilling.Probamos la conexión:

isql freeswitch pyfreebilling sesamo

+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+
SQL> quit

Activamos el acceso seguro al servidor Web:

a2enmod ssl
make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/ssl/private/localhost.pem

Capture

En lugar de dominio.org, pongan el nombre de dominio de su servidor y luego Aceptar. Instalamos python virtualenv:

pip install virtualenv
cd /usr/local
virtualenv venv --no-site-packages
chown -R root:root venv

Lo activamos:

source venv/bin/activate
cd venv

Instalamos las dependencias para CPAN:

apt-get install build-essential

Entramos en CPAN e instalamos una serie de módulos PERL:

cpan

Contestamos con las opciones predefinidas a las distintas preguntas y luego:

cpan> make install
cpan> install Bundle::CPAN
cpan> install Carp
cpan> install Filter::Simple
cpan> install Config::Vars
cpan> exit

Descargamos la ultima versión de PyFreeBilling:

git clone https://mwolff@bitbucket.org/mwolff/pyfreebilling.git

Cambiamos los permisos para que se accesible por el servidor Web:

chown -R www-data:www-data pyfreebilling

Creamos el archivo de configuración:

cd pyfreebilling

touch pyfreebilling/local_settings.py

nano pyfreebilling/local_settings.py

------

# -*- coding: utf-8 -*-
from .settings import *

DEBUG = False

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'pyfreebilling',
        'USER': 'pyfreebilling',
        'PASSWORD': 'sesamo',
        'HOST': '127.0.0.1',
        'PORT': '',                      # Set to empty string for default.
    }
}

ALLOWED_HOSTS = ['*']

SECRET_KEY = 'clave12847539330303'

TIME_ZONE = 'America/Bogota'

OPENEXCHANGERATES_APP_ID = "Your API Key"

#-- Nb days of CDR to show
PFB_NB_ADMIN_CDR = 10
PFB_NB_CUST_CDR = 60

# EMAIL SETUP
TEMPLATED_EMAIL_BACKEND = 'templated_email.backends.vanilla_django.TemplateBackend'
TEMPLATED_EMAIL_TEMPLATE_DIR = 'templated_email/'
TEMPLATED_EMAIL_FILE_EXTENSION = 'email'

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
#EMAIL_USE_TLS = Trues
EMAIL_USE_SSL = False
EMAIL_SIGNATURE = ''

------

Antes de guardar los cambios modificamos:

'PASSWORD': 'sesamo',

con la contraseña del usuario PostgreSQL pyfreebiling

SECRET_KEY = 'clave12847539330303'

con una clave aleatoria (IMPORTANTE)

Seguimos instalando todas las dependencias necesarias contenidas en el archivo requirements/requirements.txt:

pip install -r requirements/requirements.txt
python manage.py syncdb

Aparecerá:

image

Donde creamos el usuario y contraseña que utilizaremos luego para acceder a la pagina de administración de PyFreeBilling. Continuamos configurando los módulos instalados:

python manage.py initcurrencies
python manage.py migrate
python manage.py loaddata country_dialcode.json
python manage.py loaddata switch 0001_fixtures.json
python manage.py loaddata 0001_initial_SipProfile.json
python manage.py loaddata 0001_initial_ReccurentTasks.json
python manage.py loaddata country.json
python manage.py collectstatic

Al ultimo comando contestamos con yes. Ahora copiamos algunos archivos de configuración de FreeSWITCH presentes en PyFreeBilling en la carpetas de configuración de FreeSWITCH:

cp -av /usr/local/venv/pyfreebilling/freeswitch/conf/autoload_configs/acl.conf.xml /usr/local/freeswitch/conf/autoload_configs/acl.conf.xml
cp -av /usr/local/venv/pyfreebilling/freeswitch/conf/autoload_configs/cdr_csv.conf.xml /usr/local/freeswitch/conf/autoload_configs/cdr_csv.conf.xml
cp -av /usr/local/venv/pyfreebilling/freeswitch/conf/autoload_configs/modules.conf.xml /usr/local/freeswitch/conf/autoload_configs/modules.conf.xml
cp -av /usr/local/venv/pyfreebilling/freeswitch/conf/autoload_configs/nibblebill.conf.xml /usr/local/freeswitch/conf/autoload_configs/nibblebill.conf.xml
cp -av /usr/local/venv/pyfreebilling/freeswitch/dialplan/pyfreebill.xml /usr/local/freeswitch/conf/dialplan/pyfreebill.xml
cp -av /usr/local/venv/pyfreebilling/freeswitch/dialplan/public/00_did.xml /usr/local/freeswitch/conf/dialplan/public/00_did.xml
cp -av /usr/local/venv/pyfreebilling/freeswitch/conf/freeswitch.xml /usr/local/freeswitch/conf/freeswitch.xml

Copiamos los archivos binarios de Python Event Socket Library en la carpeta env:

cd /usr/src/freeswitch
cp libs/esl/python/ESL.py /usr/local/venv/lib/python2.7/site-packages/
cp libs/esl/python/_ESL.so /usr/local/venv/lib/python2.7/site-packages/

Configuramos todas una serie de permisos:

rm -f /usr/local/freeswitch/conf/directory/default/*
chown -R freeswitch:freeswitch /usr/local/venv/pyfreebilling/freeswitch/scripts/
chmod 2750 /usr/local/freeswitch
chmod 2750 /usr/local/freeswitch/conf/
chmod 2750 /usr/local/freeswitch/conf/autoload_configs/
chmod 2750 /usr/local/freeswitch/conf/directory/
chmod 2750 /usr/local/freeswitch/conf/dialplan/
chmod 2750 /usr/local/freeswitch/conf/dialplan/public/
chmod 770 /usr/local/freeswitch/conf/directory/default.xml
chmod 770 /usr/local/freeswitch/conf/autoload_configs/sofia.conf.xml
chmod 770 /usr/local/freeswitch/conf/dialplan/public/00_did.xml
chown freeswitch:www-data -R /usr/local/freeswitch/
mkdir /tmp/cdr-csv/
chmod 777 -R /tmp/cdr-csv
touch /tmp/cdr-csv/Master.csv
chmod 600 /tmp/cdr-csv/Master.csv
chown freeswitch:freeswitch /tmp/cdr-csv/Master.csv
chown -R freeswitch:daemon /tmp/cdr-csv/

Activamos la configuración de PyFreeBylling para Apache:

cp /usr/local/venv/pyfreebilling/setup/apache/001-pyfreebilling /etc/apache2/sites-enabled/000-default.conf
a2ensite 000-default
/etc/init.d/apache2 restart

Si aparece este error:

Syntax error on line 31 of /etc/apache2/sites-enabled/000-default.conf:
Invalid command '<IfVersion', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.
   ...fail
!

Creamos un enlace simbólico al modulo version de Apache:

ln -s /etc/apache2/mods-available/version.load /etc/apache2/mods-enabled/version.load

Iniciamos nuevamente Apache:

/etc/init.d/apache2 restart

Configuramos algunos procesos para que se ejecuten en automático:

crontab -e

Al final del archivo ponemos:

*/1 * * * * perl /usr/local/venv/pyfreebilling/freeswitch/scripts/import-csv.pl>> /var/log/cron.log 2>&1
* * * * * /usr/local/venv/bin/chroniker -e /usr/local/venv/bin/activate_this.py -p /usr/local/venv/pyfreebilling

Guardamos los cambios y modificamos el siguiente archivo:

nano /usr/local/venv/pyfreebilling/freeswitch/scripts/import-csv.pl

cambiando la siguiente línea:

my $pg_pwd = "password";

para que quede con la contraseña del usuario pyfreebilling de PostgreSQL:

my $pg_pwd = "sesamo";

Guardamos lo cambios y iniciamos FreeSWITCH:

/etc/init.d/freeswitch restart

Averiguamos que podemos acceder a la consola accediendo desde otra ventana terminal:

fscli

Para salir de la consola:

freeswitch@internal> ...

Ahora abrimos un navegador y accedemos a la pagina de administración de PyFreeBilling:

https://IPservidor/extranet

Capture

Ingresamos el nombre de usuario y la contraseña escogida cuando se ejecutó el comando python manage.py syncdb

En esta pagina encuentran los pasos a seguir para la configuración.

Me comentan.

Vota el Articulo: 

Sin votos (todavía)
Evalúa la calidad del articulo

2 comentarios

No pude pasar de "python manage.py initcurrencies"

Hola, quién ha podido instalarlo?, mi primer tropiezo fue en "python manage.py syncdb", lo solucioné adelantándome a las instrucciones copiando los archivos a la carpeta virtual, pero al llegar a initcurrencies de ahí no pasé, ni "migrate" ni ninguno de estos comandos:

python manage.py initcurrencies
python manage.py migrate
python manage.py loaddata country_dialcode.json
python manage.py loaddata switch 0001_fixtures.json
python manage.py loaddata 0001_initial_SipProfile.json
python manage.py loaddata 0001_initial_ReccurentTasks.json
python manage.py loaddata country.json
python manage.py updatecurrencies (if you have set your Openexchange API key)
python manage.py collectstatic (answer 'yes')

Probé con una versión actualizada de django (1.10.2) pasando por intermedias como la 1.6 llegando a la 1.5 porque en algunos casos me decía que al parecer el comando pertenecía a una versión 1.5 o anterior de django, en fin... no pude :-( .. alguien me podría colaborar?, gracias.

Suscribirse a Comentarios de "Sistema de facturación para FreeSWTCH: PyFreeBilling en Ubuntu 12.04 LTS" Suscribirse a VozToVoice - Todos los comentarios