Exemple #1
0
 def create_logger(self):
     if self._daemon is False:
         self.log = StdoutLogger()
         self.log.set_debug()
     else:
         logtype = helpers.get_conf_value(self._config,
                                             'freeswitch', 'LOG_TYPE')
         if logtype == 'file':
             logfile = helpers.get_conf_value(self._config,
                                             'freeswitch', 'LOG_FILE')
             self.log = FileLogger(logfile)
         elif logtype == 'syslog':
             syslogaddress = helpers.get_conf_value(self._config,
                                         'freeswitch', 'SYSLOG_ADDRESS')
             syslogfacility = helpers.get_conf_value(self._config,
                                         'freeswitch', 'SYSLOG_FACILITY')
             self.log = SysLogger(syslogaddress, syslogfacility)
         else:
             self.log = StdoutLogger()
         debug_mode = helpers.get_conf_value(self._config,
                                             'freeswitch', 'DEBUG')
         if debug_mode == 'true':
             self.log.set_debug()
         else:
             self.log.set_info()
Exemple #2
0
 def __init__(self, host='127.0.0.1', database='ipsafe', limit=100):
     self.log = StdoutLogger()
     self.maxsize = limit
     self.pool = Queue()
     self.size = 0
     self.host = host
     self.database = database
     self.port = 3306
     self.user = '******'
     self.password = '******'
    def create_logger(self, config):
        """This will create a logger using helpers.PlivoConfig instance

        Based on the settings in the configuration file,
        LOG_TYPE will determine if we will log in file, syslog, stdout, http or dummy (no log)
        """
        if self._daemon is False:
            logtype = config.get('rest_server', 'LOG_TYPE')
            if logtype == 'dummy':
                new_log = DummyLogger()
            else:
                new_log = StdoutLogger()
            new_log.set_debug()
            self.app.debug = True
            self.log = new_log
        else:
            logtype = config.get('rest_server', 'LOG_TYPE')
            if logtype == 'file':
                logfile = config.get('rest_server', 'LOG_FILE')
                new_log = FileLogger(logfile)
            elif logtype == 'syslog':
                syslogaddress = config.get('rest_server', 'SYSLOG_ADDRESS')
                syslogfacility = config.get('rest_server', 'SYSLOG_FACILITY')
                new_log = SysLogger(syslogaddress, syslogfacility)
            elif logtype == 'dummy':
                new_log = DummyLogger()
            elif logtype == 'http':
                url = config.get('rest_server', 'HTTP_LOG_URL')
                method = config.get('rest_server', 'HTTP_LOG_METHOD')
                fallback_file = config.get('rest_server',
                                           'HTTP_LOG_FILE_FAILURE')
                new_log = HTTPLogger(url=url,
                                     method=method,
                                     fallback_file=fallback_file)
            else:
                new_log = StdoutLogger()
            log_level = config.get('rest_server', 'LOG_LEVEL', default='INFO')
            if log_level == 'DEBUG' or self._trace is True:
                new_log.set_debug()
                self.app.debug = True
            elif log_level == 'INFO':
                new_log.set_info()
                self.app.debug = False
            elif log_level == 'ERROR':
                new_log.set_error()
                self.app.debug = False
            elif log_level in ('WARN', 'WARNING'):
                new_log.set_warn()
                self.app.debug = False

        new_log.name = self.name
        self.log = new_log
        self.app._logger = self.log
class RestServer(InboundEventSocket, RestApi):
    name = "RestServer"

    def __init__(self, configfile):
        os.environ['PLIVO_REST_CONFIG'] = configfile
        # create flask app
        self.app = Flask(self.name)
        # load config into flask app
        self.app.config.from_envvar('PLIVO_REST_CONFIG')
        # init logger
        self._init_logger()
        # create rest server
        fs_host, fs_port = self.app.config['FS_INBOUND_ADDRESS'].split(':', 1)
        fs_port = int(fs_port)
        fs_password = self.app.config['FS_PASSWORD']
        InboundEventSocket.__init__(self, fs_host, fs_port, fs_password, filter='ALL')
        # expose api functions to flask app
        for path, func_desc in urls.URLS.iteritems():
            func, methods = func_desc
            fn = getattr(self, func.__name__)
            self.app.add_url_rule(path, func.__name__, fn, methods=methods)
        # create wsgi server
        http_host, http_port = self.app.config['HTTP_ADDRESS'].split(':', 1)
        http_port = int(http_port)
        self.http_server = WSGIServer((http_host, http_port), self.app, log=self.logger)

    def _init_logger(self):
        logdebug = self.app.config.get('DEBUG', False)
        logtype = self.app.config.get('LOG_TYPE', 'stdout')
        if logtype == 'syslog':
            syslog_addr = self.app.config.get('SYSLOG_ADDRESS', '/dev/log')
            syslog_facility = self.app.config.get('SYSLOG_FACILITY', 'local0')
            self.logger = SysLogger(syslog_addr, syslog_facility)
        elif logtype == 'file':
            logfile = self.app.config.get('LOG_FILE', '/tmp/ivr.log')
            self.logger = FileLogger(logfile)
        else:
            self.logger = StdoutLogger()
        self.logger.name = self.name
        self.app._logger = self.logger
        if logdebug:
            self.logger.set_debug()
        else:
            self.logger.set_info()

    def start(self):
        # run
        #self.app.debug = True
        #self.app.run()
        #self.connect()
        self.http_server.serve_forever()
 def _init_logger(self):
     logdebug = self.app.config.get('DEBUG', False)
     logtype = self.app.config.get('LOG_TYPE', 'stdout')
     if logtype == 'syslog':
         syslog_addr = self.app.config.get('SYSLOG_ADDRESS', '/dev/log')
         syslog_facility = self.app.config.get('SYSLOG_FACILITY', 'local0')
         self.logger = SysLogger(syslog_addr, syslog_facility)
     elif logtype == 'file':
         logfile = self.app.config.get('LOG_FILE', '/tmp/ivr.log')
         self.logger = FileLogger(logfile)
     else:
         self.logger = StdoutLogger()
     self.logger.name = self.name
     self.app._logger = self.logger
     if logdebug:
         self.logger.set_debug()
     else:
         self.logger.set_info()
Exemple #6
0
    def create_logger(self):
        """This will create a logger

        Based on the settings in the configuration file,
        LOG_TYPE will determine if we will log in file, syslog or stdout

        To log in file we use the following setting :
        LOG_FILE = /tmp/plivo-rest.log

        To log to syslog we have several settings to configure the logging :
            * LOG_TYPE = syslog
            * SYSLOG_ADDRESS = /dev/log
            * SYSLOG_FACILITY = local0
        """

        if self._daemon is False:
            self.log = StdoutLogger()
            self.log.set_debug()
            self.app.debug = True
        else:
            logtype = helpers.get_conf_value(self._config,
                                                'rest_server', 'LOG_TYPE')
            if logtype == 'file':
                logfile = helpers.get_conf_value(self._config,
                                                'rest_server', 'LOG_FILE')
                self.log = FileLogger(logfile)
            elif logtype == 'syslog':
                syslogaddress = helpers.get_conf_value(self._config,
                                            'rest_server', 'SYSLOG_ADDRESS')
                syslogfacility = helpers.get_conf_value(self._config,
                                            'rest_server', 'SYSLOG_FACILITY')
                self.log = SysLogger(syslogaddress, syslogfacility)
            else:
                self.log = StdoutLogger()

            debug_mode = helpers.get_conf_value(self._config,
                                                    'rest_server', 'DEBUG')
            if  debug_mode == 'true':
                self.log.set_debug()
                self.app.debug = True
            else:
                self.log.set_info()
        self.log.name = self.name
        self.app._logger = self.log
Exemple #7
0
 def __init__(self, host='127.0.0.1', database='ipsafe', limit=100):
     self.log = StdoutLogger()
     self.maxsize = limit
     self.pool = Queue()
     self.size = 0
     self.host = host
     self.database = database
     self.port =  3306
     self.user = '******' 
     self.password = '******'
 def create_logger(self):
     if self._daemon is False:
         self.log = StdoutLogger()
         self.log.set_debug()
     else:
         logtype = helpers.get_conf_value(self._config, "freeswitch", "LOG_TYPE")
         if logtype == "file":
             logfile = helpers.get_conf_value(self._config, "freeswitch", "LOG_FILE")
             self.log = FileLogger(logfile)
         elif logtype == "syslog":
             syslogaddress = helpers.get_conf_value(self._config, "freeswitch", "SYSLOG_ADDRESS")
             syslogfacility = helpers.get_conf_value(self._config, "freeswitch", "SYSLOG_FACILITY")
             self.log = SysLogger(syslogaddress, syslogfacility)
         else:
             self.log = StdoutLogger()
         debug_mode = helpers.get_conf_value(self._config, "freeswitch", "DEBUG")
         if debug_mode == "true":
             self.log.set_debug()
         else:
             self.log.set_info()
class AsyncOutboundServer(OutboundServer):
    def __init__(self, address, handle_class, filter=None):
        self.log = StdoutLogger()
        self.log.info("Start server %s ..." % str(address))
        OutboundServer.__init__(self, address, handle_class, filter)

    def do_handle(self, socket, address):
        self.log.info("New request from %s" % str(address))
        self._handle_class(socket, address, self.log, filter=self._filter)
        self.log.info("End request from %s" % str(address))
class AsyncOutboundServer(OutboundServer):
    def __init__(self, address, handle_class, filter=None):
        self.log = StdoutLogger()
        self.log.info("Start server %s ..." % str(address))
        OutboundServer.__init__(self, address, handle_class, filter)

    def handle_request(self, socket, address):
        self.log.info("New request from %s" % str(address))
        self._requestClass(socket, address, self.log, self._filter)
        self.log.info("End request from %s" % str(address))
class MyInboundEventSocket(InboundEventSocket):
    '''Inbound eventsocket connector that automatically reconnects
    when the freeswitch eventsocket module closed the connection
    '''
    def __init__(self, host, port, password, filter="ALL", pool_size=500, connect_timeout=5):
        InboundEventSocket.__init__(self, host, port, password, filter, pool_size, connect_timeout)
        self.log = StdoutLogger()

    def start(self):
        self.log.info("Start Inbound socket %s:%d with filter %s" \
            % (self.transport.host, self.transport.port, self._filter))
        while True:
            try:
                self.connect()
                self.log.info("Inbound socket connected")
                self.serve_forever()
            except ConnectError, e:
                self.log.error("ConnectError: %s" % str(e))
            except (SystemExit, KeyboardInterrupt):
                break
            self.log.error("Inbound socket closed, try to reconnect ...")
            gevent.sleep(1.0)
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Plivo Team. See LICENSE for details.

from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.core.errors import ConnectError
from plivo.utils.logger import StdoutLogger
import gevent

def stop(inbound_event_listener, log):
    log.info("stopping now !")
    inbound_event_listener.disconnect()
    log.info("stopped !")

if __name__ == '__main__':
    log = StdoutLogger()
    try:
        inbound_event_listener = InboundEventSocket('127.0.0.1', 8021, 'ClueCon', filter="ALL")
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit('exit')

        log.info("stopping in 5 seconds !")
        gevent.spawn_later(5, stop, inbound_event_listener, log)

        inbound_event_listener.serve_forever()

    except (SystemExit, KeyboardInterrupt): pass

    log.info("exit")
    def on_background_job(self, ev):
        '''
        Recieves callbacks for BACKGROUND_JOB event.
        '''
        self.jobqueue.set(ev)

    def wait_background_job(self):
        '''
        Waits until BACKGROUND_JOB event was caught and returns Event.
        '''
        return self.jobqueue.get()


if __name__ == '__main__':
    log = StdoutLogger()
    try:
        inbound_event_listener = MyEventSocket('127.0.0.1',
                                               8021,
                                               'ClueCon',
                                               filter="BACKGROUND_JOB",
                                               log=log)
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit('exit')

        fs_bg_api_string = "originate user/1000 &playback(/usr/local/freeswitch/sounds/en/us/callie/base256/8000/liberty.wav)"
        bg_api_response = inbound_event_listener.bgapi(fs_bg_api_string)
        log.info(str(bg_api_response))
    bg_api_response = inbound_event_listener.bgapi(fs_bg_api_string)
    log.info(str(bg_api_response))
    job_uuid = bg_api_response.get_job_uuid()
    if not job_uuid:
        log.error("bgapi %s: job uuid not found" % fs_bg_api_string)
        return
    inbound_event_listener.track_job(job_uuid)
    log.info("bgapi %s => Job-UUID %s" % (fs_bg_api_string, job_uuid))
    log.info("waiting job %s ..." % job_uuid)
    ev = inbound_event_listener.wait_for_job(job_uuid)

    log.info("bgapi %s => %s" % (fs_bg_api_string, str(ev.get_body())))


if __name__ == '__main__':
    log = StdoutLogger()
    try:
        inbound_event_listener = MyEventSocket('127.0.0.1', 8021, 'ClueCon', filter="BACKGROUND_JOB", log=log)
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit('exit')
        if not CONTACTS:
            log.error("No CONTACTS !")
            raise SystemExit('exit')
        pool = gevent.pool.Pool(len(CONTACTS))
        for contact in CONTACTS:
            pool.spawn(spawn_originate, inbound_event_listener, contact, log)
        pool.join()
        log.debug("all originate commands done")
    def on_background_job(self, ev):
        """
        Recieves callbacks for BACKGROUND_JOB event.
        """
        self.jobqueue.set(ev)

    def wait_background_job(self):
        """
        Waits until BACKGROUND_JOB event was caught and returns Event.
        """
        return self.jobqueue.get()


if __name__ == "__main__":
    log = StdoutLogger()
    try:
        inbound_event_listener = MyEventSocket("127.0.0.1", 8021, "ClueCon", filter="BACKGROUND_JOB", log=log)
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit("exit")

        fs_bg_api_string = (
            "originate user/1000 &playback(/usr/local/freeswitch/sounds/en/us/callie/base256/8000/liberty.wav)"
        )
        bg_api_response = inbound_event_listener.bgapi(fs_bg_api_string)
        log.info(str(bg_api_response))
        log.info(bg_api_response.get_response())
        if not bg_api_response.is_success():
Exemple #16
0
class PlivoOutboundServer(outboundsocket.OutboundServer):
    def __init__(self, configfile, daemon=False,
                    pidfile='/tmp/plivo_outbound.pid'):
        self._request_id = 0
        self._daemon = daemon
        self._run = False
        self._pidfile = pidfile
        # load config
        self._config = helpers.get_config(configfile)
        # set trace flag
        self._trace = helpers.get_conf_value(self._config,
                            'freeswitch', 'FS_OUTBOUND_TRACE') == 'true'
        # create logger
        self.create_logger()
        # create outbound server
        self.fs_outbound_address = helpers.get_conf_value(self._config,
                                        'freeswitch', 'FS_OUTBOUND_ADDRESS')
        fs_host, fs_port = self.fs_outbound_address.split(':', 1)
        fs_port = int(fs_port)
        self.default_answer_url = helpers.get_conf_value(self._config,
                                        'freeswitch', 'DEFAULT_ANSWER_URL')
        self.auth_id = helpers.get_conf_value(self._config,
                                        'rest_server', 'AUTH_ID')
        self.auth_token = helpers.get_conf_value(self._config,
                                        'rest_server', 'AUTH_TOKEN')
        self.default_hangup_url = helpers.get_conf_value(self._config,
                                        'freeswitch', 'DEFAULT_HANGUP_URL')
        self.default_http_method = helpers.get_conf_value(self._config,
                                        'rest_server', 'DEFAULT_HTTP_METHOD')
        if not self.default_http_method in ('GET', 'POST'):
            self.default_http_method = 'POST'

        self.extra_fs_vars = helpers.get_conf_value(self._config,
                                            'freeswitch', 'EXTRA_FS_VARS')

        # This is where we define the connection with the
        # Plivo XML element Processor
        outboundsocket.OutboundServer.__init__(self, (fs_host, fs_port),
                                PlivoOutboundEventSocket, filter=None)

    def _get_request_id(self):
        try:
            self._request_id += 1
        except OverflowError:
            self._request_id = 1
        return self._request_id

    def handle_request(self, socket, address):
        request_id = self._get_request_id()
        self.log.info("(%d) New request from %s" % (request_id, str(address)))
        self._requestClass(socket, address, self.log,
                           default_answer_url=self.default_answer_url,
                           default_hangup_url=self.default_hangup_url,
                           default_http_method=self.default_http_method,
                           extra_fs_vars=self.extra_fs_vars,
                           auth_id=self.auth_id,
                           auth_token=self.auth_token,
                           request_id=request_id,
                           trace=self._trace
                           )
        self.log.info("(%d) End request from %s" % (request_id, str(address)))

    def create_logger(self):
        if self._daemon is False:
            logtype = helpers.get_conf_value(self._config,
                                                'freeswitch', 'LOG_TYPE')
            if logtype == 'dummy':
                self.log = DummyLogger()
            else:
                self.log = StdoutLogger()
            self.log.set_debug()
        else:
            logtype = helpers.get_conf_value(self._config,
                                                'freeswitch', 'LOG_TYPE')
            if logtype == 'file':
                logfile = helpers.get_conf_value(self._config,
                                                'freeswitch', 'LOG_FILE')
                self.log = FileLogger(logfile)
            elif logtype == 'syslog':
                syslogaddress = helpers.get_conf_value(self._config,
                                            'freeswitch', 'SYSLOG_ADDRESS')
                syslogfacility = helpers.get_conf_value(self._config,
                                            'freeswitch', 'SYSLOG_FACILITY')
                self.log = SysLogger(syslogaddress, syslogfacility)
            elif logtype == 'dummy':
                self.log = DummyLogger()
            else:
                self.log = StdoutLogger()
            debug_mode = helpers.get_conf_value(self._config,
                                                'freeswitch', 'DEBUG')
            if debug_mode == 'true' or self._trace is True:
                self.log.set_debug()
            else:
                self.log.set_info()

    def do_daemon(self):
        # get user/group from config
        user = helpers.get_conf_value(self._config,
                                    'freeswitch', 'FS_OUTBOUND_USER')
        group = helpers.get_conf_value(self._config,
                                    'freeswitch', 'FS_OUTBOUND_GROUP')
        if not user or not group:
            uid = os.getuid()
            user = pwd.getpwuid(uid)[0]
            gid = os.getgid()
            group = grp.getgrgid(gid)[0]
        # daemonize now
        plivo.utils.daemonize.daemon(user, group, path='/',
                                    pidfile=self._pidfile, other_groups=())

    def sig_term(self, *args):
        self.stop()
        self.log.warn("Shutdown ...")
        sys.exit(0)

    def start(self):
        self.log.info("Starting OutboundServer ...")
        # catch SIG_TERM
        gevent.signal(signal.SIGTERM, self.sig_term)
        # run
        self._run = True
        if self._daemon:
            self.do_daemon()
        super(PlivoOutboundServer, self).start()
        self.log.info("OutboundServer started at '%s'" \
                                    % str(self.fs_outbound_address))
        self.serve_forever()
        self.log.info("OutboundServer Exited")
Exemple #17
0
# Copyright (c) 2011 Plivo Team. See LICENSE for details.

from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.core.errors import ConnectError
from plivo.utils.logger import StdoutLogger
import gevent


def stop(inbound_event_listener, log):
    log.info("stopping now !")
    inbound_event_listener.disconnect()
    log.info("stopped !")


if __name__ == '__main__':
    log = StdoutLogger()
    try:
        inbound_event_listener = InboundEventSocket('127.0.0.1',
                                                    8021,
                                                    'ClueCon',
                                                    filter="ALL")
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit('exit')

        log.info("stopping in 5 seconds !")
        gevent.spawn_later(5, stop, inbound_event_listener, log)

        inbound_event_listener.serve_forever()
 def __init__(self, host, port, password, filter="ALL", pool_size=500, connect_timeout=5):
     InboundEventSocket.__init__(self, host, port, password, filter, pool_size, connect_timeout)
     self.log = StdoutLogger()
Exemple #19
0
class PlivoRestServer(PlivoRestApi):
    """Class PlivoRestServer"""
    name = "PlivoRestServer"

    def __init__(self, configfile, daemon=False,
                        pidfile='/tmp/plivo_rest.pid'):
        """Constructor

        Initialize main properties such as daemon, pidfile, config, etc...

        This will init the http server that will provide the Rest interface,
        the rest server is configured on HTTP_ADDRESS

        Extra:
        * FS_INBOUND_ADDRESS : Define the event_socket interface to connect to
        in order to initialize CallSession with Freeswitch

        * FS_OUTBOUND_ADDRESS : Define where on which address listen to
        initialize event_socket session with Freeswitch in order to control
        new CallSession

        """
        self._daemon = daemon
        self._run = False
        self._pidfile = pidfile
        # load config
        self._config = helpers.get_config(configfile)
        # create flask app
        self.app = Flask(self.name)
        self.app.secret_key = helpers.get_conf_value(self._config,
                                                'rest_server', 'SECRET_KEY')
        self.app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
        # create logger
        self.create_logger()
        # create rest server
        self.fs_inbound_address = helpers.get_conf_value(self._config,
                                        'freeswitch', 'FS_INBOUND_ADDRESS')
        fs_host, fs_port = self.fs_inbound_address.split(':', 1)
        fs_port = int(fs_port)
        fs_password = helpers.get_conf_value(self._config,
                                                'freeswitch', 'FS_PASSWORD')
        # get auth id and auth token
        self.auth_id = helpers.get_conf_value(self._config,
                                        'rest_server', 'AUTH_ID')
        self.auth_token = helpers.get_conf_value(self._config,
                                        'rest_server', 'AUTH_TOKEN')
        # get outbound socket host/port
        fs_out_address = helpers.get_conf_value(self._config,
                                        'freeswitch', 'FS_OUTBOUND_ADDRESS')
        fs_out_host, fs_out_port  = fs_out_address.split(':', 1)
        # if outbound host is 0.0.0.0, send to 127.0.0.1
        if fs_out_host == '0.0.0.0':
            fs_out_address = '127.0.0.1:%s' % fs_out_port
        # create inbound socket instance
        self._rest_inbound_socket = RESTInboundSocket(fs_host, fs_port,
                                                    fs_password, 
                                                    outbound_address=fs_out_address,
                                                    auth_id=self.auth_id,
                                                    auth_token=self.auth_token,
                                                    filter='ALL',
                                                    log=self.log)
        # expose api functions to flask app
        for path, func_desc in urls.URLS.iteritems():
            func, methods = func_desc
            fn = getattr(self, func.__name__)
            self.app.add_url_rule(path, func.__name__, fn, methods=methods)
        # create wsgi server
        self.http_address = helpers.get_conf_value(self._config,
                                            'rest_server', 'HTTP_ADDRESS')
        http_host, http_port = self.http_address.split(':', 1)
        http_port = int(http_port)
        self.http_server = WSGIServer((http_host, http_port),
                                       self.app, log=self.log)

    def create_logger(self):
        """This will create a logger

        Based on the settings in the configuration file,
        LOG_TYPE will determine if we will log in file, syslog or stdout

        To log in file we use the following setting :
        LOG_FILE = /tmp/plivo-rest.log

        To log to syslog we have several settings to configure the logging :
            * LOG_TYPE = syslog
            * SYSLOG_ADDRESS = /dev/log
            * SYSLOG_FACILITY = local0
        """

        if self._daemon is False:
            self.log = StdoutLogger()
            self.log.set_debug()
            self.app.debug = True
        else:
            logtype = helpers.get_conf_value(self._config,
                                                'rest_server', 'LOG_TYPE')
            if logtype == 'file':
                logfile = helpers.get_conf_value(self._config,
                                                'rest_server', 'LOG_FILE')
                self.log = FileLogger(logfile)
            elif logtype == 'syslog':
                syslogaddress = helpers.get_conf_value(self._config,
                                            'rest_server', 'SYSLOG_ADDRESS')
                syslogfacility = helpers.get_conf_value(self._config,
                                            'rest_server', 'SYSLOG_FACILITY')
                self.log = SysLogger(syslogaddress, syslogfacility)
            else:
                self.log = StdoutLogger()

            debug_mode = helpers.get_conf_value(self._config,
                                                    'rest_server', 'DEBUG')
            if  debug_mode == 'true':
                self.log.set_debug()
                self.app.debug = True
            else:
                self.log.set_info()
        self.log.name = self.name
        self.app._logger = self.log

    def do_daemon(self):
        """This will daemonize the current application

        Two settings from our configuration files are also used to run the
        daemon under a determine user & group.

        REST_SERVER_USER : determine the user running the daemon
        REST_SERVER_GROUP : determine the group running the daemon
        """
        # get user/group from config
        user = helpers.get_conf_value(self._config,
                                        'rest_server', 'REST_SERVER_USER')
        group = helpers.get_conf_value(self._config,
                                        'rest_server', 'REST_SERVER_GROUP')
        if not user or not group:
            uid = os.getuid()
            user = pwd.getpwuid(uid)[0]
            gid = os.getgid()
            group = grp.getgrgid(gid)[0]
        # daemonize now
        plivo.utils.daemonize.daemon(user, group, path='/',
                                     pidfile=self._pidfile, 
                                     other_groups=())

    def sig_term(self, *args):
        """if we receive a term signal, we will shutdown properly
        """
        self.log.warn("Shutdown ...")
        self.stop()
        sys.exit(0)

    def stop(self):
        """Method stop stop the infinite loop from start method
        and close the socket
        """
        self._run = False
        self._rest_inbound_socket.exit()

    def start(self):
        """start method is where we decide to :
            * catch term signal
            * run as daemon
            * start the http server
            * connect to Freeswitch via our Inbound Socket interface
            * wait even if it takes forever, ever, ever, evveeerrr...
        """
        self.log.info("RESTServer starting ...")
        # catch SIG_TERM
        gevent.signal(signal.SIGTERM, self.sig_term)
        # run
        self._run = True
        if self._daemon:
            self.do_daemon()
        # connection counter
        retries = 1
        # start http server
        self.http_proc = gevent.spawn(self.http_server.serve_forever)
        self.log.info("RESTServer started at: 'http://%s'" % self.http_address)
        # start inbound socket
        try:
            while self._run:
                try:
                    self.log.info("Trying to connect to FreeSWITCH at: %s" \
                                            % self.fs_inbound_address)
                    self._rest_inbound_socket.connect()
                    # reset retries when connection is a success
                    retries = 1
                    self.log.info("Connected to FreeSWITCH")
                    # serve forever
                    self._rest_inbound_socket.serve_forever()
                except ConnectError, e:
                    if self._run is False:
                        break
                    self.log.error("Connect failed: %s" % str(e))
                # sleep after connection failure
                sleep_for = retries * 10
                self.log.error("Reconnecting in %d seconds" % sleep_for)
                gevent.sleep(sleep_for)
                # don't sleep more than 120 secs
                if retries < 12:
                    retries += 1
        except (SystemExit, KeyboardInterrupt):
            pass
        # kill http server
        self.http_proc.kill()
        # finish here
        self.log.info("RESTServer Exited")
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Plivo Team. See LICENSE for details.

from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.core.errors import ConnectError
from plivo.utils.logger import StdoutLogger

if __name__ == '__main__':
    log = StdoutLogger()
    try:
        inbound_event_listener = InboundEventSocket('127.0.0.1', 8021, 'ClueCon', filter="BACKGROUND_JOB")
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit('exit')

        fs_bg_api_string = "originate user/1000 &playback(/usr/local/freeswitch/sounds/en/us/callie/base256/8000/liberty.wav)"
        bg_api_response = inbound_event_listener.bgapi(fs_bg_api_string)
        log.info(str(bg_api_response))
        log.info(bg_api_response.get_response())
        if not bg_api_response.is_success():
            log.error("bgapi failed !")
            raise SystemExit('exit')

        job_uuid = bg_api_response.get_job_uuid()
        if not job_uuid:
            log.error("bgapi jobuuid not found !")
            raise SystemExit('exit')

        log.info("bgapi success with Job-UUID " + job_uuid)
def dispatch_requests(env, start_response):
    if env['PATH_INFO'] == '/':
        if CONTACTS:
            start_response('200 OK', [('Content-Type', 'text/html')])

            #Put logic to handle the request each time
            pool = gevent.pool.Pool(len(CONTACTS))
            jobs = [pool.spawn(spawn_originate, inbound_event_listener, contact, log) for contact in CONTACTS]
            gevent.joinall(jobs)
            log.debug("All originate commands done")

            return ["<b>Executed Request</b>"]

    start_response('404 Not Found', [('Content-Type', 'text/html')])
    return ['<h1>Wrong Usage - Command Not found</h1>']


if __name__ == '__main__':
    log = StdoutLogger()
    #Connect to freeswitch ESL in inbound mode
    inbound_event_listener = MyEventSocket('127.0.0.1', 8021, 'ClueCon', filter="ALL", log=log)
    try:
        inbound_event_listener.connect()
    except ConnectError, e:
        log.error("connect failed: %s" % str(e))
        raise SystemExit('exit')

    #Connect to freeswitch ESL in inbound mode
    wsgi.WSGIServer(('', 8088), dispatch_requests).serve_forever()
Exemple #22
0
class DBConnection(object):
    def __init__(self, host='127.0.0.1', database='ipsafe', limit=100):
        self.log = StdoutLogger()
        self.maxsize = limit
        self.pool = Queue()
        self.size = 0
        self.host = host
        self.database = database
        self.port = 3306
        self.user = '******'
        self.password = '******'

    def get(self):
        self.log.info("[+] DBConnection.get")
        try:
            return self.pool.get_nowait()
        except:
            if self.size >= self.maxsize or self.pool.qsize():
                return self.pool.get()
            else:
                self.size += 1
                try:
                    new_item = umysql.Connection()
                    new_item.connect(self.host, self.port, self.user,
                                     self.password, self.database)
                except:
                    self.size -= 1
                    raise
                return new_item

    def put(self, item):
        self.log.info("[+] DBConnection.put")
        self.pool.put(item)

    def closeall(self):
        while not self.pool.empty():
            conn = self.pool.get_nowait()
            try:
                conn.close()
            except Exception:
                pass

    @contextlib.contextmanager
    def connection(self):
        self.log.info("[+] DBConnection.connection")
        conn = self.get()
        try:
            yield conn
        except:
            if not conn.is_connected():
                conn = None
                self.closeall()
            else:
                conn = self._rollback(conn)
            raise
        finally:
            if conn is not None and conn.is_connected():
                self.put(conn)

    @contextlib.contextmanager
    def query(self, *args, **kwargs):
        self.log.info("[+] DBConnection.query")
        with self.connection() as conn:
            try:
                yield conn.query(*args, **kwargs)
            except Exception, e:
                print("[-] Error = " + str(e))
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Plivo Team. See LICENSE for details.

from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.core.errors import ConnectError
from plivo.utils.logger import StdoutLogger

if __name__ == '__main__':
    log = StdoutLogger()
    try:
        inbound_event_listener = InboundEventSocket('127.0.0.1', 8021, 'ClueCon', filter="ALL")
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit('exit')

        filter_response = inbound_event_listener.filter("Event-Name CHANNEL_ANSWER")
        log.info(str(filter_response))
        if not filter_response.is_success():
            log.error("filter failed with response %s" % filter_response.get_response())
            raise SystemExit('exit')

        log.info("filter success with response %s" % filter_response.get_response())

    except (SystemExit, KeyboardInterrupt): pass

    log.info("exit")
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Plivo Team. See LICENSE for details.

import traceback
from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.utils.logger import StdoutLogger

if __name__ == '__main__':
    log = StdoutLogger()

    log.info('#' * 60)
    log.info("Connect with bad host")
    try:
        inbound_event_listener = InboundEventSocket('falsehost', 8021,
                                                    'ClueCon')
        inbound_event_listener.connect()
    except:
        [log.info(line) for line in traceback.format_exc().splitlines()]
    log.info('#' * 60 + '\n')

    log.info('#' * 60)
    log.info("Connect with bad port")
    try:
        inbound_event_listener = InboundEventSocket('127.0.0.1', 9999999,
                                                    'ClueCon')
        inbound_event_listener.connect()
    except:
        [log.info(line) for line in traceback.format_exc().splitlines()]
    log.info('#' * 60 + '\n')

    log.info('#' * 60)
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Plivo Team. See LICENSE for details.

from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.core.errors import ConnectError
from plivo.utils.logger import StdoutLogger

if __name__ == '__main__':
    log = StdoutLogger()
    try:
        inbound_event_listener = InboundEventSocket('127.0.0.1', 8021, 'ClueCon', filter="ALL")
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit('exit')

        log.info("stopping now !")
        inbound_event_listener.disconnect()

    except (SystemExit, KeyboardInterrupt): pass

    log.info("exit")
Exemple #26
0
# coding=utf-8

from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.core.errors import ConnectError
from plivo.utils.logger import StdoutLogger

from config import event_socket_conf as conf

log = StdoutLogger()
inbound_event_listener = None


def api(cmd, bg=False, ok_check=True):
    global inbound_event_listener
    data = {}
    if not inbound_event_listener:
        inbound_event_listener = InboundEventSocket(conf['host'],
                                                    conf['port'],
                                                    conf['pwd'],
                                                    filter="BACKGROUND_JOB")
    if not inbound_event_listener.connected:
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            return {'code': -9, 'msg': 'connect failed !', 'data': data}
    fs_bg_api_string = cmd
    if bg:
        bg_api_response = inbound_event_listener.bgapi(fs_bg_api_string)
    else:
        bg_api_response = inbound_event_listener.api(fs_bg_api_string)
Exemple #27
0
# coding=utf-8

from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.core.errors import ConnectError
from plivo.utils.logger import StdoutLogger

log = StdoutLogger()


def api(cmd, bg=False, ok_check=True):
    #global inbound_event_listener
    import event_socket
    inbound_event_listener = event_socket.inbound_event_listener
    data = {}
    if not inbound_event_listener:
        try:
            event_socket.connect()
        except Exception, e:
            log.error("connect failed: %s" % str(e))
            return {'code': -9, 'msg': 'connect failed !', 'data': data}
    if not inbound_event_listener.connected:
        try:
            inbound_event_listener.connect()
        except Exception, e:
            log.error("connect failed: %s" % str(e))
            return {'code': -9, 'msg': 'connect failed !', 'data': data}
    fs_bg_api_string = cmd
    if bg:
        bg_api_response = inbound_event_listener.bgapi(fs_bg_api_string)
    else:
        bg_api_response = inbound_event_listener.api(fs_bg_api_string)
Exemple #28
0
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Plivo Team. See LICENSE for details.

from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.core.errors import ConnectError
from plivo.utils.logger import StdoutLogger

if __name__ == '__main__':
    log = StdoutLogger()
    try:
        inbound_event_listener = InboundEventSocket('127.0.0.1',
                                                    8021,
                                                    'ClueCon',
                                                    filter="BACKGROUND_JOB")
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit('exit')

        fs_bg_api_string = "originate user/1000 &playback(/usr/local/freeswitch/sounds/en/us/callie/base256/8000/liberty.wav)"
        bg_api_response = inbound_event_listener.bgapi(fs_bg_api_string)
        log.info(str(bg_api_response))
        log.info(bg_api_response.get_response())
        if not bg_api_response.is_success():
            log.error("bgapi failed !")
            raise SystemExit('exit')

        job_uuid = bg_api_response.get_job_uuid()
        if not job_uuid:
            log.error("bgapi jobuuid not found !")
 def __init__(self, address, handle_class, filter=None):
     self.log = StdoutLogger()
     self.log.info("Start server %s ..." % str(address))
     OutboundServer.__init__(self, address, handle_class, filter)
Exemple #30
0
            pool = gevent.pool.Pool(len(CONTACTS))
            jobs = [
                pool.spawn(spawn_originate, inbound_event_listener, contact,
                           log) for contact in CONTACTS
            ]
            gevent.joinall(jobs)
            log.debug("All originate commands done")

            return ["<b>Executed Request</b>"]

    start_response('404 Not Found', [('Content-Type', 'text/html')])
    return ['<h1>Wrong Usage - Command Not found</h1>']


if __name__ == '__main__':
    log = StdoutLogger()
    #Connect to freeswitch ESL in inbound mode
    inbound_event_listener = MyEventSocket('127.0.0.1',
                                           8021,
                                           'ClueCon',
                                           filter="ALL",
                                           log=log)
    try:
        inbound_event_listener.connect()
    except ConnectError, e:
        log.error("connect failed: %s" % str(e))
        raise SystemExit('exit')

    #Connect to freeswitch ESL in inbound mode
    wsgi.WSGIServer(('', 8088), dispatch_requests).serve_forever()
 def __init__(self, address, handle_class, filter=None):
     self.log = StdoutLogger()
     self.log.info("Start server %s ..." % str(address))
     OutboundServer.__init__(self, address, handle_class, filter)
Exemple #32
0
class DBConnection(object):
    def __init__(self, host='127.0.0.1', database='ipsafe', limit=100):
        self.log = StdoutLogger()
        self.maxsize = limit
        self.pool = Queue()
        self.size = 0
        self.host = host
        self.database = database
        self.port =  3306
        self.user = '******' 
        self.password = '******'

    def get(self):
        self.log.info("[+] DBConnection.get")
        try:
            return self.pool.get_nowait()
        except:
            if self.size >= self.maxsize or self.pool.qsize():
                return self.pool.get()
            else:
                self.size += 1
                try:
                    new_item = umysql.Connection()
                    new_item.connect(self.host, self.port, self.user, self.password, self.database)
                except:
                    self.size -= 1
                    raise
                return new_item

    def put(self, item):
        self.log.info("[+] DBConnection.put")
        self.pool.put(item)  
       
    def closeall(self):
        while not self.pool.empty():
            conn = self.pool.get_nowait()
            try:
                conn.close()
            except Exception:
                pass 

    @contextlib.contextmanager
    def connection(self):
        self.log.info("[+] DBConnection.connection")
        conn = self.get()
        try:
            yield conn
        except:
            if not conn.is_connected():
                conn = None
                self.closeall()
            else:
                conn = self._rollback(conn)
            raise
        finally:
            if conn is not None and conn.is_connected():
                self.put(conn)

    @contextlib.contextmanager
    def query(self, *args, **kwargs):
        self.log.info("[+] DBConnection.query")
        with self.connection() as conn:
            try:
                yield conn.query(*args, **kwargs)
            except Exception, e:
                print("[-] Error = " + str(e))
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Plivo Team. See LICENSE for details.

import traceback
from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.utils.logger import StdoutLogger

if __name__ == '__main__':
    log = StdoutLogger()

    log.info('#'*60)
    log.info("Connect with bad host")
    try:
        inbound_event_listener = InboundEventSocket('falsehost', 8021, 'ClueCon')
        inbound_event_listener.connect()
    except:
        [ log.info(line) for line in traceback.format_exc().splitlines() ]
    log.info('#'*60 + '\n')

    log.info('#'*60)
    log.info("Connect with bad port")
    try:
        inbound_event_listener = InboundEventSocket('127.0.0.1', 9999999, 'ClueCon')
        inbound_event_listener.connect()
    except:
        [ log.info(line) for line in traceback.format_exc().splitlines() ]
    log.info('#'*60 + '\n')

    log.info('#'*60)
    log.info("Connect with bad password")
    try:
class PlivoOutboundServer(OutboundServer):
    def __init__(self, configfile, daemon=False, pidfile="/tmp/plivo_outbound.pid", filter=None):
        self._request_id = 0
        self._daemon = daemon
        self._run = False
        self._pidfile = pidfile
        # load config
        self._config = helpers.get_config(configfile)
        # create logger
        self.create_logger()
        # create outbound server
        self.fs_outbound_address = helpers.get_conf_value(self._config, "freeswitch", "FS_OUTBOUND_ADDRESS")
        fs_host, fs_port = self.fs_outbound_address.split(":", 1)
        fs_port = int(fs_port)
        self.default_answer_url = helpers.get_conf_value(self._config, "freeswitch", "DEFAULT_ANSWER_URL")
        self.auth_id = helpers.get_conf_value(self._config, "rest_server", "AUTH_ID")
        self.auth_token = helpers.get_conf_value(self._config, "rest_server", "AUTH_TOKEN")
        self.default_hangup_url = helpers.get_conf_value(self._config, "freeswitch", "DEFAULT_HANGUP_URL")
        # default hangup_url is answer_url
        if not self.default_hangup_url:
            self.default_hangup_url = self.default_answer_url
        # This is where we define the connection with the
        # Plivo XML grammar Processor
        OutboundServer.__init__(self, (fs_host, fs_port), PlivoOutboundEventSocket, filter)

    def _get_request_id(self):
        try:
            self._request_id += 1
        except OverflowError:
            self._request_id = 1
        return self._request_id

    def do_handle(self, socket, address):
        request_id = self._get_request_id()
        self.log.info("(%d) New request from %s" % (request_id, str(address)))
        self._handle_class(
            socket,
            address,
            self.log,
            default_answer_url=self.default_answer_url,
            default_hangup_url=self.default_hangup_url,
            auth_id=self.auth_id,
            auth_token=self.auth_token,
            request_id=request_id,
            filter=self._filter,
        )
        self.log.info("(%d) End request from %s" % (request_id, str(address)))

    def create_logger(self):
        if self._daemon is False:
            self.log = StdoutLogger()
            self.log.set_debug()
        else:
            logtype = helpers.get_conf_value(self._config, "freeswitch", "LOG_TYPE")
            if logtype == "file":
                logfile = helpers.get_conf_value(self._config, "freeswitch", "LOG_FILE")
                self.log = FileLogger(logfile)
            elif logtype == "syslog":
                syslogaddress = helpers.get_conf_value(self._config, "freeswitch", "SYSLOG_ADDRESS")
                syslogfacility = helpers.get_conf_value(self._config, "freeswitch", "SYSLOG_FACILITY")
                self.log = SysLogger(syslogaddress, syslogfacility)
            else:
                self.log = StdoutLogger()
            debug_mode = helpers.get_conf_value(self._config, "freeswitch", "DEBUG")
            if debug_mode == "true":
                self.log.set_debug()
            else:
                self.log.set_info()

    def do_daemon(self):
        # get user/group from config
        user = helpers.get_conf_value(self._config, "freeswitch", "FS_OUTBOUND_USER")
        group = helpers.get_conf_value(self._config, "freeswitch", "FS_OUTBOUND_GROUP")
        if not user or not group:
            uid = os.getuid()
            user = pwd.getpwuid(uid)[0]
            gid = os.getgid()
            group = grp.getgrgid(gid)[0]
        # daemonize now
        plivo.utils.daemonize.daemon(user, group, path="/", pidfile=self._pidfile, other_groups=())

    def sig_term(self, *args):
        self.stop()
        self.log.warn("Shutdown ...")
        sys.exit(0)

    def stop(self):
        self._run = False
        self.kill()

    def start(self):
        self.log.info("Starting OutboundServer ...")
        # catch SIG_TERM
        gevent.signal(signal.SIGTERM, self.sig_term)
        # run
        self._run = True
        if self._daemon:
            self.do_daemon()
        super(PlivoOutboundServer, self).start()
        self.log.info("OutboundServer started at '%s'" % str(self.fs_outbound_address))
        try:
            while self._run:
                gevent.sleep(1.0)
        except (SystemExit, KeyboardInterrupt):
            pass
        self.log.info("OutboundServer Exited")
Exemple #35
0
# -*- coding: utf-8 -*-
# Copyright (c) 2011 Plivo Team. See LICENSE for details.

from plivo.core.freeswitch.inboundsocket import InboundEventSocket
from plivo.core.errors import ConnectError
from plivo.utils.logger import StdoutLogger

if __name__ == '__main__':
    log = StdoutLogger()
    try:
        inbound_event_listener = InboundEventSocket('127.0.0.1', 8021, 'ClueCon', filter="ALL")
        try:
            inbound_event_listener.connect()
        except ConnectError, e:
            log.error("connect failed: %s" % str(e))
            raise SystemExit('exit')

        fs_api_string = "originate user/1000 &playback(/usr/local/freeswitch/sounds/en/us/callie/base256/8000/liberty.wav)"
        api_response = inbound_event_listener.api(fs_api_string)
        log.info(str(api_response))
        if not api_response.is_success():
            log.error("api failed with response %s" % api_response.get_response())
            raise SystemExit('exit')

        log.info("api success with response %s" % api_response.get_response())

    except (SystemExit, KeyboardInterrupt): pass

    log.info("exit")
Exemple #36
0
 def __init__(self, host, port, password, filter="ALL", log=None):
     InboundEventSocket.__init__(self, host, port, password, filter)
     self.log = log or StdoutLogger()