Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- #
- # LookupSessionDB module
- #
- # $Id$
- #
- import logging
- from twisted.enterprise import adbapi
- from Base import Base, ParamError
- __version__ = "$Revision$"
- class LookupSessionDB(Base):
- """LookupSessionDB module
- Module arguments (see output of getParams method):
- param, recipient
- Check arguments:
- data ... all input data in dict
- Check returns:
- 1 .... ok
- 0 .... undefined (default for this module)
- -1 ... failed
- Examples:
- # make instance of LookupSessionDB module
- modules['lists_client_address'] = ( 'LookupSessionDB', {'table': 'recipient_results'} )
- """
- PARAMS = { 'table': ('database where to dump the recipient results', 'recipient_results'),
- }
- # copied from protocol.py
- def _getDbPool(self):
- if self.factory.config.get('databaseAPI') == None:
- raise Exception("undefined databaseAPI")
- if self.dbPool == None:
- self.dbPool = adbapi.ConnectionPool(self.factory.config.get('databaseAPI'),
- **self.factory.config.get('database_session'))
- # self.dbPool.start()
- return self.dbPool
- def _getDbConnection(self):
- return self._getDbPool().connect()
- def start(self):
- """Called when changing state to 'started'. Right now it is called
- only when you start ppolicy daemon (but in future it can be called
- e.g. during reloading configuration files).
- You can check here e.g. module parameters (test1, test2, ...)
- if values defined in ppolicy.conf doesn't contain wrong values."""
- if self.factory == None:
- raise ParamError("this module need reference to factory and database connection pool")
- table = self.getParam('table')
- if table == None:
- raise ParamError('table has to be specified for this module')
- self.dbPool = None
- def stop(self):
- """Called when changing state to 'stopped'. As for start this is
- called only during exit of ppolicy daemon.
- You can cleanly release resources used by this module (e.g. close
- opened file hanles, network connections, ...)."""
- pass
- def hashArg(self, data, *args, **keywords):
- """Compute hash from data which is then used as index
- to the result cache. Changing this function in subclasses
- and using only required fields for computing hash can
- improve cache usage and performance.
- arguments:
- data -- input data
- args -- array of arguments defined in ppolicy.conf
- keywords -- dict of arguments defined in ppolicy.conf
- example:
- If your check method use only sender address than the result
- is only dependend on this one parameter (and not on recipient,
- client_address, ...). So for best cache performance you should
- return value that depends only on sender address:
- return hash(data.get('sender', ''))
- If you return 0 it means that check method result will not
- be cached.
- """
- return 0
- def check(self, data, *args, **keywords):
- """check request data againts policy and returns tuple of status
- code and optional info. The meaning of status codes is folloving:
- < 0 check failed
- = 0 check uknown (e.g. required resource not available)
- > 0 check succeded
- parameters:
- data -- input data
- args -- array of arguments defined in ppolicy.conf
- keywords -- dict of arguments defined in ppolicy.conf
- """
- # default return values
- ret, retEx = 0, None
- table = self.getParam('table')
- sql = "SELECT `res`, `resEx` FROM `%s` WHERE `instance` = '%s'" % (table, data.get('instance'))
- logging.getLogger().debug("sql: %s" % (sql))
- try:
- conn = self._getDbConnection()
- cursor = conn.cursor()
- conn.commit()
- except Exception, e:
- logging.getLogger().error("database error %s" % (e))
- ret, retEx = 0, "database error %s" % (e)
- else:
- retryCounter = 2
- while retryCounter > 0:
- try:
- retryCounter -= 1
- cursor.execute(sql)
- rows = cursor.fetchall()
- for row in rows:
- logging.getLogger().debug(row)
- if row[0] == 'OK':
- ret, retEx = 1, 0
- cursor.close()
- break
- cursor.close()
- # No exception until now, don't retry
- retryCounter = 0
- except Exception, e:
- if e.__class__.__name__ == 'OperationalError' and (e.args[0] == 2013 or e.args[0] == 2006):
- # Reconnect
- try:
- conn.ping(True)
- except:
- pass
- logging.getLogger().error("database error %s - reconnecting" % (e))
- else:
- try:
- cursor.close()
- except:
- pass
- logging.getLogger().error("database error %s" % (e))
- # Retry on MySQLdb.OperationalError, only
- retryCounter = 0
- ret, retEx = 0, "database error %s" % (e)
- return ret, retEx
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement