Ejemplo n.º 1
0
    def modcommand(self, arg):

        # get args
        args = arg.split(RequestHandler.DELIM_MODCOMMAND)

        # check arg-count
        if len(args) != 2:
            return Result(arg, Exception('invalid arg-count for modcommand'))

        # get vars from args
        moduleName = args[0]
        moduleCommand = args[1]

        # get ModuleManager-instance
        moduleManager = Activator().getInstance('ModuleManager')

        # call command
        data = moduleManager.moduleCommand(moduleName, moduleCommand)

        # if data is none, return none
        if data is None:
            return None
 
        # return result
        return Result(data, None)
Ejemplo n.º 2
0
    def reloadModules(self, args):

        # get ModuleManager-instance
        moduleManager = Activator().getInstance('ModuleManager')

        # get Dispatcher-instance
        dispatcher = Activator().getInstance('Dispatcher')

        # stop ModuleManager if running
        try:
            if moduleManager.isModuleRunning():
                # stop
                moduleManager.stopModule()
                # check if we got a running module
                tries = 0
                triesMax = 75
                nap = 0.2
                isRunning = True
                while isRunning and tries < triesMax:
                    time.sleep(nap)
                    tries += 1
                    isRunning = moduleManager.isModuleRunning()
                if isRunning:
                    raise Exception, "Modules running after %d seconds" % (triesMax * nap)
        except Exception, e:
            self.logger.error("Error when stopping ModuleManager (%s)" % (e))
            # return result
            return Result('Error when stopping ModuleManager', e)
Ejemplo n.º 3
0
    def invoke(self):

        # invocation-count
        self.runCount += 1

        try:

            # get Fluxcli instance
            fluxcli = Activator().getInstance('Fluxcli')
            
            # process jobs
            jobCopy = self.jobs[:]
            for job in jobCopy:
            
                # build arg-array
                args = []
                args.append('rss')
                args.append(job['savedir'])
                args.append('%s%s.dat' % (self.dataDir, job['filtername']))
                args.append('%s%s.hist' % (self.dataDir, job['filtername']))
                args.append(job['url'])
                
                # execute job
                try:
                    # log run
                    self.logger.debug('running rssad-job: %s' % job.__str__())
                    # invoke fluxcli
                    result = fluxcli.invoke(args, True).strip()
                    # log result
                    self.logger.debug('rssad-run-result:\n%s' % result)
                except Exception, e:
                    self.logger.error("Error when calling rssad (%s)" % (e))

            # return
            return True
Ejemplo n.º 4
0
def transferStart(name):

    # imports
    from fluxd.activator.Activator import Activator

    # get Fluxcli-instance
    fluxcli = Activator().getInstance('Fluxcli')

    # invoke fluxcli
    try:
        # invoke and return
        return fluxcli.invoke(['start', name], True).strip()
    except Exception, e:
        raise Exception, "Exception when invoking fluxcli to start transfer %s (%s)" % (name, e)
Ejemplo n.º 5
0
class BasicModule(IModule):

    # lock
    InstanceLock = Lock()

    """ -------------------------------------------------------------------- """
    """ __init__                                                             """
    """ -------------------------------------------------------------------- """
    def __init__(self, name, *p, **k):

        # set name
        self.name = name

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

        # request-handler
        self.requestHandler = None

        # onStop-delegates
        self.onStopDelegates = []

        # running-flag
        self.running = False

        # listener-thread
        self.thread = Thread(target = self.run)
        self.thread.setName(self.name)
        self.thread.setDaemon(True)

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

        # log
        self.logger.info("up and running")

        # running-flag
        self.running = True

        # module-main
        try:
            self.main()
        except Exception, e:
            if self.running:
                self.logger.error("Exception in Module-Thread (%s)" % (e))

        # shutdown
        self.shutdown()
Ejemplo n.º 6
0
    def modstate(self, args):

        # mod-name
        module = args[0].strip()

        # get ModuleManager-instance
        moduleManager = Activator().getInstance('ModuleManager')

        mstate = '0'
        if moduleManager.isModuleRunning(module):
            mstate = '1'

        # return result
        return Result(mstate, None)
Ejemplo n.º 7
0
    def __init__(self, name):

        # set name
        self.__name = name

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

        # onStop-delegates
        self.__onStopDelegates = []

        # request-queue
        self.__queueRequest = Queue()

        # request-handler
        self.__requestHandler = RequestHandler(self.logger)

        # running-flag
        self.__running = False

        # request-count
        self.requestCount = 0

        # thread
        self.__thread = Thread(target = self.run)
        self.__thread.setName(self.__name)
        self.__thread.setDaemon(True)
Ejemplo n.º 8
0
    def __init__(self, name):

        # set name
        self.__name = name

        # logger
        self.logger = Activator().getInstance('LoggerFactory').getLogger('ModuleManager')
    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)
Ejemplo n.º 10
0
class DatabaseManager(IActivator):

    # instance
    Instance = None

    # lock
    InstanceLock = Lock()

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

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

        # set name
        self.__name = name

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

        # settings
        self.settings = {}

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

    """ -------------------------------------------------------------------- """
    """ getSetting                                                           """
    """ -------------------------------------------------------------------- """
    def getSetting(self, key):
        try:
            return self.settings[key]
        except Exception, e:
            self.logger.error("Exception in getSetting: %s" % (e))
            raise Exception, "Failed to get Setting: %s" % (key)
Ejemplo n.º 11
0
    def modstop(self, args):

        # mod-name
        module = args[0].strip()

        # get ModuleManager-instance
        moduleManager = Activator().getInstance('ModuleManager')

        # check if running
        if not moduleManager.isModuleRunning(module):
            return Result('Module not running: %s' % module, None)

        # stop it
        try:
            moduleManager.stopModule(module)
        except Exception, e:
            # return result
            return Result('Error when stopping Module: %s' % module, e)
Ejemplo n.º 12
0
    def invoke(self):

        # invocation-count
        self.runCount += 1

        try:

            # get Fluxcli instance
            fluxcli = Activator().getInstance("Fluxcli")

            # process jobs
            jobCopy = self.jobs[:]
            for job in jobCopy:

                # build arg-array
                args = []
                args.append("watch")
                args.append(job["D"])  # watchdir
                args.append(job["U"])  # user
                if job.has_key("A"):  # action
                    action = job["A"]
                else:
                    action = "ds"
                extraargs = []
                if job.has_key("P"):  # profile
                    action += "p"
                    extraargs.append(job["P"])
                args.append(action)
                args += extraargs

                # execute job
                try:
                    # log run
                    self.logger.debug("running watch-job: %s" % job.__str__())
                    # invoke fluxcli
                    result = fluxcli.invoke(args, True).strip()
                    # log result
                    self.logger.debug("watch-run-result:\n%s" % result)
                except Exception, e:
                    self.logger.error("Error when calling watch (%s)" % (e))

            # return
            return True
Ejemplo n.º 13
0
    def __init__(self, name):

        # set name
        self.__name = name

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

        # invocation-Count
        self.invocationCount = 0
Ejemplo n.º 14
0
    def __init__(self, name):

        # set name
        self.__name = name

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

        # settings
        self.settings = {}
    def __init__(self):

        # logger
        self.logger = Activator().getInstance('LoggerFactory').getLogger('DataAdapterADOdb')
        
        # db-config
        self.dbConfig = None
        
        # connection
        self.connection = None
Ejemplo n.º 16
0
    def invoke(self):

        # invocation-count
        self.runCount += 1

        try:
            
            # get Fluxcli instance
            fluxcli = Activator().getInstance('Fluxcli')
            
            # invoke
            result = fluxcli.invoke(['maintenance', self.restart], True).strip()
            
            # log
            self.logger.debug('maintenance-run-result:\n%s' % result)
            
            # return
            return True
        
        except Exception, e:
            self.logger.error("Error when calling maintenance (%s)" % (e))
Ejemplo n.º 17
0
    def modstart(self, args):

        # mod-name
        module = args[0].strip()

        # get ModuleManager-instance
        moduleManager = Activator().getInstance('ModuleManager')

        # check if running
        if moduleManager.isModuleRunning(module):
            return Result('Module already running: %s' % module, None)

        # get Dispatcher-instance
        dispatcher = Activator().getInstance('Dispatcher') 

        # start it
        try:
            moduleManager.startModule(dispatcher.requestHandler, module)
        except Exception, e:
            # return result
            return Result('Error when starting Module: %s' % module, e)
Ejemplo n.º 18
0
    def modlist(self, args):

        # get ModuleManager-instance
        moduleManager = Activator().getInstance('ModuleManager')

        # get module-list
        modules = Config().get('modules', 'Modules').strip().split(',')

        # build list
        data = ''
        for module in modules:
            module = module.strip()
            mstate = '0'
            if moduleManager.isModuleRunning(module):
                mstate = '1'
            data += '%s%s%s%s' % (RequestHandler.DELIM_MOD, module, RequestHandler.DELIM_MODSTATE, mstate)
        if len(data) > 1:
            data = data[1:]

        # return result
        return Result(data, None)
Ejemplo n.º 19
0
    def __init__(self, name, *p, **k):

        # set name
        self.name = name

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

        # request-handler
        self.requestHandler = None

        # onStop-delegates
        self.onStopDelegates = []

        # running-flag
        self.running = False

        # listener-thread
        self.thread = Thread(target = self.run)
        self.thread.setName(self.name)
        self.thread.setDaemon(True)
Ejemplo n.º 20
0
    def reloadDBCache(self, args):

        # get DatabaseManager-instance
        databaseManager = Activator().getInstance('DatabaseManager')

        # database-load
        databaseManager.load()

        # get ModuleManager-instance
        moduleManager = Activator().getInstance('ModuleManager')

        # Signal the loaded modules to come and check if they need to update
        # themselves
        modmsg = ''
        for module in moduleManager.runningModules():
            data = moduleManager.moduleCommand(module, 'reloadConfig')
            modmsg += '%s: %s\n' % (module, data)

        # return result
        return Result('Database-Config reloaded (%s)\n%s' % (str(databaseManager.getSettingsCount()), modmsg), None)
Ejemplo n.º 21
0
                # invoke fluxcli
                try:
                    # invoke
                    fluxcli.invoke(['pm', 'Trigger', new.transferowner.strip(), name + ' has met criteria: ' + event], False)
                except Exception, e:
                    raise Exception, 'Exception when attempting to pm the user: %s' % e

            return self.removeJob(name, event, action)

        elif action.startswith('tset'):
            """ adjust transfer settings."""
            # check the parameters
            (setting, value) = action.split(Trigger.CmdDelim)[1:]

            # get fluxcli instance
            fluxcli = Activator().getInstance('Fluxcli');

            # invoke fluxcli
            try:
                fluxcli.invoke(['tset', name, setting, value], True).strip()
            except Exception, e:
                raise Exception, "Exception when attempting to adjust torrent settings"

            return self.removeJob(name, event, action)

        elif action.startswith('unzip'):
            # don't find the files, get them directly from the user!
            files = action.split(Trigger.CmdDelim)[1:]
            for file in files:
                try:
                    # Get the file's extension
Ejemplo n.º 22
0
    def status(self, args):

        # get Fluxcli-instance
        fluxcli = Activator().getInstance('Fluxcli')

        # get DatabaseManager-instance
        databaseManager = Activator().getInstance('DatabaseManager')

        # get ServerManager-instance
        serverManager = Activator().getInstance('ServerManager')

        # get ModuleManager-instance
        moduleManager = Activator().getInstance('ModuleManager')

        # get Dispatcher-instance
        dispatcher = Activator().getInstance('Dispatcher')

        # get server-list
        servers = serverManager.runningServers()

        # get module-list
        modules = moduleManager.runningModules()

        # data
        data = ''

        # status
        data += '----------------------------------------------------------------\n'
        data += ' Status\n'
        data += '----------------------------------------------------------------\n'

        # thread-count
        data += '%d Threads active\n' % activeCount()

        # server-count
        data += '%d Servers running\n' % len(servers)

        # module-count
        data += '%d Modules running\n' % len(modules)

        # dispatcher request-count
        data += '%d Dispatcher-Requests\n' % dispatcher.requestCount

        # fluxcli invocations
        data += '%d Fluxcli invocations\n' % fluxcli.invocationCount

        # database-settings
        data += '%d Database-Settings loaded\n' % databaseManager.getSettingsCount()

        # threads
        data += '\n----------------------------------------------------------------\n'
        data += ' Threads\n'
        data += '----------------------------------------------------------------\n'
        for thr in enumerate():
            data += '%s (isDaemon: %s)\n' % (thr.getName(), str(thr.isDaemon()))

        # servers
        data += '\n----------------------------------------------------------------\n'
        data += ' Servers\n'
        data += '----------------------------------------------------------------\n'
        for server in servers:
            data += '\n[%s]\n' % server
            serverStatus = serverManager.serverStatus(server)
            if serverStatus is not None:
                for key, val in serverStatus.iteritems():
                    data += '%s: %s\n' % (key, val)

        # modules
        data += '\n----------------------------------------------------------------\n'
        data += ' Modules\n'
        data += '----------------------------------------------------------------\n'
        for module in modules:
            data += '\n[%s]\n' % module
            moduleStatus = moduleManager.moduleStatus(module)
            if moduleStatus is not None:
                for key, val in moduleStatus.iteritems():
                    data += '%s: %s\n' % (key, val)

        # config
        data += '\n----------------------------------------------------------------\n'
        data += ' Config\n'
        data += '----------------------------------------------------------------\n'
        data += Config().currentConfigAsIniString()

        # return result
        return Result(data, None)
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
Ejemplo n.º 24
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
Ejemplo n.º 25
0
class ModuleManager(IActivator):

    # instance
    Instance = None

    # lock
    InstanceLock = Lock()

    # modules
    Modules = {}

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

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

        # set name
        self.__name = name

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

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

    """ -------------------------------------------------------------------- """
    """ startModule                                                          """
    """ -------------------------------------------------------------------- """
    @synchronized(InstanceLock)
    def startModule(self, requestHandler, name = None):
        try:

            # start all modules
            if name is None:
                self.logger.info('Starting all Modules...')
                names = Config().get('modules', 'Modules').strip().split(',')
                for name in names:
                    name = name.strip()
                    if isTrue(Config().getExt(name, 'enabled').strip()):
                        try:
                            # check if exists
                            if ModuleManager.Modules.has_key(name):
                                raise Exception, "Module does already exist: %s" % (name)
                            # start
                            ModuleManager.Modules[name] = getClassByName(Config().get(name, 'module').strip(), Config().get(name, 'class').strip())(name)
                            ModuleManager.Modules[name].start(requestHandler, self.onModuleStop)
                        except Exception, e:
                            self.logger.error("failed to start Module %s (%s)" % (name, e))

            # start single module
            else:
Ejemplo n.º 26
0
class Dispatcher(IActivator):

    # instance
    Instance = None

    # lock
    InstanceLock = Lock()

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

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

        # set name
        self.__name = name

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

        # onStop-delegates
        self.__onStopDelegates = []

        # request-queue
        self.__queueRequest = Queue()

        # request-handler
        self.__requestHandler = RequestHandler(self.logger)

        # running-flag
        self.__running = False

        # request-count
        self.requestCount = 0

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

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

    """ -------------------------------------------------------------------- """
    """ start                                                              """
    """ -------------------------------------------------------------------- """
    def start(self):

        # log
        self.logger.info('Starting...')

        # start thread
        self.__thread.start()

    """ -------------------------------------------------------------------- """
    """ stop                                                                 """
    """ -------------------------------------------------------------------- """
    def stop(self):

        # running-flag
        self.__running = False

        # join
        self.__thread.join(2.0)

        # shutdown if still alive
        if self.__thread.isAlive():
            self.shutdown()

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

        # running-flag
        self.__running = True

        # debug
        self.logger.info("up and running")

        # main-loop
        while self.__running:

            # process queue
            try:
                # get and process request
                request = self.__queueRequest.get()
                # handle request
                self.__running = self.__requestHandler.handleRequest(request)
            except Empty, emp:
                self.logger.error("request-queue is empty (%s)" % emp)
            except Exception, e:
                self.logger.error("failed to process request (%s)" % e)
Ejemplo n.º 27
0
    def _fireEventCore(self, event, name, action, new):
        """actually call the event."""

        if action.startswith('execute'):
            script = action.split(Trigger.CmdDelim)[1]

            # pass stuff to the environment
            params = {}
            params[Trigger.Param_CURDATE]  = time.strftime(Config().get('logging', 'Dateformat'))
            params[Trigger.Param_DOCROOT]  = Config().get('dir', 'docroot').strip()
            params[Trigger.Param_EVENT]    = event
            params[Trigger.Param_FLUXCLI]  = Activator().getInstance('Fluxcli').getPath()
            params[Trigger.Param_FLUXD]    = Config().get('dir', 'pathFluxd').strip()
            params[Trigger.Param_OWNER]    = new.transferowner.strip()
            params[Trigger.Param_PATH]     = Config().get('dir', 'pathTf').strip()
            params[Trigger.Param_PHP]      = Config().get('file', 'php').strip()
            params[Trigger.Param_TRANSFER] = name 
            #params[Trigger.Param_TYPE]    = type
            params[Trigger.Param_RUNNING]  = new.running
            params[Trigger.Param_PERCENT]  = new.percent_done
            params[Trigger.Param_TIME]     = new.time_left
            params[Trigger.Param_DOWN]     = new.down_speed
            params[Trigger.Param_UP]       = new.up_speed
            params[Trigger.Param_SEEDS]    = new.seeds
            params[Trigger.Param_PEERS]    = new.peers
            params[Trigger.Param_SHARING]  = new.sharing
            params[Trigger.Param_SEEDLIM]  = new.seedlimit
            params[Trigger.Param_UPTOTAL]  = new.uptotal
            params[Trigger.Param_DOWNTOTAL]= new.downtotal
            params[Trigger.Param_SIZE]     = new.size

            # Prepare environment (clean up and add params).
            env = dict([(k, v) for k, v in os.environ.iteritems() if not k.startswith(Trigger.ParamPrefix)])
            env.update(params)

            bgShellCmd(self.logger, self.name + ':' + event, script, Config().get('dir', 'pathTf').strip(), env)
            return self.removeJob(name, event, action)

        elif action.startswith('email'):
            """ Attempt to email the user, and fall back to PM if necessary."""
            try:
                # Can't get the email out of the DB at this time
                # it must be inserted into the job initially.
                
                recipient = action.split(Trigger.CmdDelim)[1]
                sender = '*****@*****.**'
                msg = MIMEText('%s has met criteria: %s' % (name, event))
                msg['Subject'] = 'Update from Torrentflux-B4rt'
                msg['From'] = sender
                msg['To'] = recipient
                
                # actually send the message. could require setting the host
                # and port on some systems.
                s = smtplib.SMTP()
                s.connect()
                s.sendmail(sender, [recipient], msg.as_string())
                s.close()
            except Exception, e:
                """ email failed, fallback to PM"""

                # log
                self.logger.error('cannot email, falling back to PM: %s' % e)

                # get fluxcli instance
                fluxcli = Activator().getInstance('Fluxcli');

                # invoke fluxcli
                try:
                    # invoke
                    fluxcli.invoke(['pm', 'Trigger', new.transferowner.strip(), name + ' has met criteria: ' + event], False)
                except Exception, e:
                    raise Exception, 'Exception when attempting to pm the user: %s' % e
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