class SocketRequestDispatcher(object):

    # lock
    InstanceLock = Lock()

    # delim
    DELIM = '\n'

    """ -------------------------------------------------------------------- """
    """ __init__                                                             """
    """ -------------------------------------------------------------------- """
    def __init__(self, name, address, socket, requestHandler, onCloseDelegate = None):

        # logger
        self.logger = Activator().getInstance('LoggerFactory').getLogger('RequestDispatcher')

        # set name
        self.__name = name

        # set address
        self.__address = address

        # set socket
        self.__socket = socket

        # request-handler
        self.__requestHandler = requestHandler

        # onClose-delegates
        self.__onCloseDelegates = []
        if not onCloseDelegate is None:
            self.__onCloseDelegates.append(onCloseDelegate)

        # result-queue
        self.__queueResult = Queue()

        # done-flag
        self.__done = False

        # running-flag
        self.__running = False

        # thread
        self.__thread = Thread(target = self.run)
        self.__thread.setName(self.__name)
        self.__thread.setDaemon(True)

    """ -------------------------------------------------------------------- """
    """ run                                                                  """
    """ -------------------------------------------------------------------- """
    def run(self):

        # running-flag
        self.__running = True

        # handle request
        self.handleRequest()

        # get and process result
        while self.__running and not self.__done:

            try:
                # get result from queue
                result = self.__queueResult.get()
                # handle result
                self.handleResult(result)
            except Empty, emp:
                self.logger.debug("result-queue is empty (%s) (%s)" % (self.__name, emp))
            except Exception, e:
                self.logger.error("failed to process queue (%s) (%s)" % (self.__name, e))
                # running-flag
                self.__running = False
class DataAdapterADOdb(IDataAdapter):

    """ -------------------------------------------------------------------- """
    """ __init__                                                             """
    """ -------------------------------------------------------------------- """
    def __init__(self):

        # logger
        self.logger = Activator().getInstance('LoggerFactory').getLogger('DataAdapterADOdb')
        
        # db-config
        self.dbConfig = None
        
        # connection
        self.connection = None

    """ -------------------------------------------------------------------- """
    """ loadSettings                                                         """
    """ -------------------------------------------------------------------- """
    def loadSettings(self):
    
        # info
        self.logger.info('loading settings...')

        # try/finally (separate this for python < 2.5)
        try:

            # try
            try:

                # open connection
                self.openConnection()

                # execute select and get cursor
                cursor = self.connection.Execute('SELECT tf_key, tf_value FROM tf_settings')

                # retval
                retVal = {}
                
                # process rows
                while not cursor.EOF:
                
                    # get row-dict
                    rowDict = cursor.GetRowAssoc(0)
                    
                    # add setting
                    retVal[rowDict['tf_key']] = rowDict['tf_value']
                    
                    # next
                    cursor.MoveNext()

                # close cursor
                cursor.Close()

                # check
                if len(retVal) < 1:
                    raise Exception, 'settings-validation failed'

                # return
                return retVal

            # catch, log and rethrow
            except Exception, e:
                self.logger.error('failed to load Settings (%s)' % (e))
                raise e

        # finally close the con
        finally:
            self.closeConnection()

    """ -------------------------------------------------------------------- """
    """ saveSettings                                                         """
    """ -------------------------------------------------------------------- """
    def saveSettings(self, settings = {}):
    
        # info
        self.logger.info('saving settings...')

        # try/finally (separate this for python < 2.5)
        try:

            # try
            try:

                # open connection
                self.openConnection()
                
                # update settings
                try:
                
                    # begin transaction
                    self.connection.BeginTrans()
                
                    # update
                    for key, val in settings.iteritems():
                    
                        # sql
                        sql = 'UPDATE tf_settings SET tf_value = %s WHERE tf_key = %s' % \
                            (self.connection.qstr(val), self.connection.qstr(key))

                        # DEBUG
                        #self.logger.debug(sql)

                        # execute update and get cursor
                        cursor = self.connection.Execute(sql)

                        # close cursor
                        cursor.Close()

                    # commit transaction
                    self.connection.CommitTrans()

                # catch, rollback and rethrow
                except Exception, e:
                    self.connection.RollbackTrans()
                    raise e

            # catch, log and rethrow
            except Exception, e:
                self.logger.error('failed to save Settings (%s)' % (e))
                raise e

        # finally close the con
        finally:
            self.closeConnection()

    """ -------------------------------------------------------------------- """
    """ openConnection                                                       """
    """ -------------------------------------------------------------------- """
    def openConnection(self):
    
        # debug
        self.logger.debug('open connection...')
    
        # get config
        try:
            self.dbConfig = getDatabaseConfig()
        # catch, log and rethrow
        except Exception, e:
            self.logger.error('failed to get database-config (%s)' % (e))
            raise e
 
        # mysql
        if self.dbConfig['db_type'].lower().startswith('mysql'):
        
            # get ado-connection
            try:
                self.connection = adodb.NewADOConnection('mysql')
                if self.connection is None: raise Exception, 'connection is None'
            # catch, log and rethrow
            except Exception, e:
                self.logger.error('failed to get ADOConnection (%s)' % (e))
                raise e

            # connect
            try:
                 self.connection.Connect(self.dbConfig['db_host'], self.dbConfig['db_user'], self.dbConfig['db_pass'], self.dbConfig['db_name'])
            # catch, log and rethrow
            except Exception, e:
                self.logger.error('failed to connect to database (%s)' % (e))
                raise e
Esempio n. 3
0
class Fluxcli(IActivator):

    # instance
    Instance = None

    # lock
    InstanceLock = Lock()

    # path (relative to docroot)
    Path = 'bin/fluxcli.php'

    """ -------------------------------------------------------------------- """
    """ __new__                                                              """
    """ -------------------------------------------------------------------- """
    def __new__(cls, *p, **k):
        if Fluxcli.Instance is None:
            Fluxcli.Instance = object.__new__(cls, *p, **k)
        return Fluxcli.Instance

    """ -------------------------------------------------------------------- """
    """ __init__                                                             """
    """ -------------------------------------------------------------------- """
    def __init__(self, name):

        # set name
        self.__name = name

        # logger
        self.logger = Activator().getInstance('LoggerFactory').getLogger('Fluxcli')

        # invocation-Count
        self.invocationCount = 0

    """ -------------------------------------------------------------------- """
    """ getName                                                              """
    """ -------------------------------------------------------------------- """
    def getName(self):
        return self.__name

    """ -------------------------------------------------------------------- """
    """ getPath                                                              """
    """ -------------------------------------------------------------------- """
    def getPath(self):
        return '%s%s' % (Config().get('dir', 'docroot').strip(), Fluxcli.Path)

    """ -------------------------------------------------------------------- """
    """ invoke                                                               """
    """ -------------------------------------------------------------------- """
    @synchronized(InstanceLock)
    def invoke(self, args = [], readResult = True):

        # increment counter
        self.invocationCount += 1

        # log
        self.logger.info('invoking fluxcli...')

        try:

            # unshift fluxcli-arg
            args.insert(0, self.getPath())

            # unshift php-arg (command is invoked thru an args
            # list, not by building a string command-line given
            # to a shell -- this avoids any quoting troubles)
            php = Config().get('file', 'php').strip()
            args.insert(0, php)

            # log pseudo-cmdline (see above, php is not actually invoked that way)
            self.logger.debug(' '.join([("'%s'" % arg) for arg in args]))

            # open
            if readResult:
                # invoke (use popen2.Popen3 directly to be able to reap
                # child correctly -- using os.popen2 leaves zombies)
                p = popen2.Popen3(args)
                p.tochild.close()
                result = p.fromchild.read()
                p.fromchild.close()
                p.wait()
                # return result
                return result

            # spawn
            else:
                # invoke and return bool
                return (os.spawnv(os.P_WAIT, php, args) == 0)

        except Exception, e:
            self.logger.error("Exception in invoke: %s" % (e))
            raise e