Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • DM/dm-docs
  • hammonds/dm-docs
  • hparraga/dm-docs
3 results
Show changes
Showing
with 925 additions and 0 deletions
#!/usr/bin/env python
#######################################################################
DM_OK = 0
DM_ERROR = 1
DM_CONFIGURATION_ERROR = 2
DM_INTERNAL_ERROR = 3
DM_INVALID_ARGUMENT_ERROR = 4
DM_INVALID_REQUEST_ERROR = 5
DM_COMMAND_FAILED_ERROR = 6
#!/usr/bin/env python
#
# Command failed exception class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class CommandFailed(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_COMMAND_FAILED_ERROR, **kwargs)
#!/usr/bin/env python
#
# Configuration error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class ConfigurationError(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_CONFIGURATION_ERROR, **kwargs)
#!/usr/bin/env python
#
# Base DM exception class.
#
#######################################################################
import exceptions
import json
from dm.common.constants import dmStatus
#######################################################################
class DmException(exceptions.Exception):
"""
Base DM exception class.
Usage:
DmException(errorMessage, errorCode)
DmException(args=errorMessage)
DmException(exception=exceptionObject)
"""
def __init__(self, error='', code=dmStatus.DM_ERROR, **kwargs):
args = error
if args == '':
args = kwargs.get('args', '')
ex = kwargs.get('exception', None)
if ex != None:
if isinstance(ex, exceptions.Exception):
exArgs = '%s' % (ex)
if args == '':
args = exArgs
else:
args = "%s (%s)" % (args, exArgs)
exceptions.Exception.__init__(self, args)
self._code = code
def getArgs(self):
return self.args
def getErrorCode(self):
return self._code
def getErrorMessage(self):
return '%s' % (self.args)
def getClassName(self):
return '%s' % (self.__class__.__name__)
def getExceptionType(self):
return '%s' % (self.__class__.__name__).split('.')[-1]
def getJsonRep(self):
return json.dumps({
'errorMessage' : self.getErrorMessage(),
'errorCode' : self.getErrorCode(),
'exceptionType' : self.getExceptionType(),
})
#!/usr/bin/env python
#
# DM exception map
#
#######################################################################
from dm.common.constants import dmStatus
exceptionMap = {
dmStatus.DM_ERROR : 'dmException.DmException',
dmStatus.DM_CONFIGURATION_ERROR : 'configurationError.ConfigurationError',
dmStatus.DM_INTERNAL_ERROR : 'internalError.InternalError',
dmStatus.DM_INVALID_ARGUMENT_ERROR : 'invalidArgument.InvalidArgument',
dmStatus.DM_INVALID_REQUEST_ERROR : 'invalidRequest.InvalidRequest',
dmStatus.DM_COMMAND_FAILED_ERROR : 'commandFailed.CommandFailed',
}
#######################################################################
# Testing
if __name__ == '__main__':
for item in exceptionMap.items():
print item
#!/usr/bin/env python
#
# Internal error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InternalError(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INTERNAL_ERROR, **kwargs)
#!/usr/bin/env python
#
# Invalid argument error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InvalidArgument(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INVALID_ARGUMENT_ERROR, **kwargs)
#!/usr/bin/env python
#
# Invalid request error class.
#
#######################################################################
from dm.common.constants import dmStatus
from dm.common.exceptions.dmException import DmException
#######################################################################
class InvalidRequest(DmException):
def __init__ (self, error='', **kwargs):
DmException.__init__(self, error, dmStatus.DM_INVALID_REQUEST_ERROR, **kwargs)
#!/usr/bin/env python
#
# DM Object class.
#
#######################################################################
import UserDict
import UserList
import types
import json
from dm.common.exceptions.invalidArgument import InvalidArgument
from dm.common.utility import loggingManager
class DmObject(UserDict.UserDict):
""" Base dm object class. """
def __init__(self, dict={}):
if isinstance(dict, types.DictType):
UserDict.UserDict.__init__(self, dict)
elif isinstance(dict, UserDict.UserDict):
UserDict.UserDict.__init__(self, dict.data)
else:
raise InvalidArgument('DmObject must be initialized using dictionary.')
self._jsonPreprocessKeyList = []
self._logger = None
def getLogger(self):
if not self._logger:
self._logger = loggingManager.getLogger(self.__class__.__name__)
return self._logger
@classmethod
def getFromDict(cls, dict):
inst = cls()
for key in dict.keys():
inst[key] = dict[key]
return inst
def getDictRep(self):
# Dict representation is dict
dictRep = {}
for (key,obj) in self.data.items():
if isinstance(obj, DmObject):
dictRep[key] = obj.getDictRep()
else:
if obj is not None:
dictRep[key] = obj
return dictRep
def getDictJsonPreprocessedRep(self):
dictRep = self.getDictRep()
# Convert designated keys into string values.
for key in self._jsonPreprocessKeyList:
value = dictRep.get(key)
if value is not None:
dictRep[key] = '%s' % value
return dictRep
def getJsonRep(self):
dictRep = self.getDictJsonPreprocessedRep()
return json.dumps(dictRep)
@classmethod
def fromJsonString(cls, jsonString):
return cls.getFromDict(json.loads(jsonString))
#######################################################################
# Testing.
if __name__ == '__main__':
x = {'name' : 'XYZ', 'one':1, 'two':2 }
o = DmObject(x)
print 'DM Object: ', o
print 'Type of DM object: ', type(o)
print 'JSON Rep: ', o.getJsonRep()
print 'Type of JSON rep: ', type(o.getJsonRep())
j = '{"name" : "XYZ", "one":1, "two":2 }'
print 'String: ', j
x2 = DmObject.fromJsonString(j)
print 'DM Object 2: ', x2
print 'Type of DM object 2: ', type(x2)
#!/usr/bin/env python
#
# Base object manager class.
#
#######################################################################
import threading
from dm.common.utility import loggingManager
#######################################################################
class DmObjectManager:
""" Base object manager class. """
def __init__(self):
self._logger = loggingManager.getLogger(self.__class__.__name__)
self._lock = threading.RLock()
def getLogger(self):
return self._logger
def acquireLock(self):
self._lock.acquire()
def releaseLock(self):
self._lock.release()
#!/usr/bin/env python
#
# Authorization controller class
#
#######################################################################
import cherrypy
import urllib
from cherrypy.lib import httpauth
from dm.common.constants import dmStatus
from dm.common.constants import dmRole
from dm.common.exceptions.dmException import DmException
from dm.common.exceptions.dmHttpError import DmHttpError
from dm.common.exceptions.authorizationError import AuthorizationError
from dm.common.utility import loggingManager
from dm.common.service.dmController import DmController
from dm.common.impl import authManager
import dmSession
#######################################################################
cherrypy.lib.sessions.DmSession = dmSession.DmSession
SESSION_USERNAME_KEY = '_cp_username'
SESSION_ROLE_KEY = 'role'
def checkCredentials(username, password):
""" Verifies credentials for username and password."""
logger = loggingManager.getLogger('checkCredentials')
logger.debug('Checking credential for User: %s, Password: %s' % (username, password))
logger.debug('Session id: %s' % cherrypy.serving.session.id)
principal = authManager.getInstance().getAuthPrincipal(username, password)
logger.debug('Principal: %s' % (principal))
if principal:
cherrypy.session[SESSION_ROLE_KEY] = principal.getRole()
logger.debug('Successful login from user: %s (role: %s)' % (username, principal.getRole()))
else:
logger.debug('Login denied for user: %s' % username)
username = cherrypy.session.get(SESSION_USERNAME_KEY, None)
if username is not None:
cherrypy.request.login = None
cherrypy.session[dmSession.INVALID_DM_SESSION_KEY] = True
raise AuthorizationError('Incorrect username or password.')
return principal
def parseBasicAuthorizationHeaders():
try:
logger = loggingManager.getLogger('parseBasicAuthorizationHeader')
username = None
password = None
authorization = cherrypy.request.headers['authorization']
authorizationHeader = httpauth.parseAuthorization(authorization)
logger.debug('Authorization header: %s' % authorizationHeader)
if authorizationHeader['auth_scheme'] == 'basic':
username = authorizationHeader['username']
password = authorizationHeader['password']
logger.debug('Got username/password from headers: %s/%s' % (username, password))
if username and password:
return (username, password)
else:
raise AuthorizationError('Username and/or password not supplied.')
except Exception, ex:
errorMsg = 'Could not extract username/password from authorization header: %s' % ex
raise AuthorizationError(errorMsg)
def checkAuth(*args, **kwargs):
"""
A tool that looks in config for 'auth.require'. If found and it
is not None, a login is required and the entry is evaluated as a list of
conditions that the user must fulfill.
"""
logger = loggingManager.getLogger('checkAuth')
conditions = cherrypy.request.config.get('auth.require', None)
logger.debug('Headers: %s' % (cherrypy.request.headers))
logger.debug('Request params: %s' % (cherrypy.request.params))
logger.debug('Request query string: %s' % (cherrypy.request.query_string))
method = urllib.quote(cherrypy.request.request_line.split()[0])
params = urllib.quote(cherrypy.request.request_line.split()[1])
logger.debug('Session: %s' % ((cherrypy.session.__dict__)))
if conditions is not None:
sessionId = cherrypy.serving.session.id
sessionCache = cherrypy.session.cache
logger.debug('Session: %s' % ((cherrypy.session.__dict__)))
logger.debug('Session cache length: %s' % (len(sessionCache)))
logger.debug('Session cache: %s' % (sessionCache))
# Check session.
if not sessionCache.has_key(sessionId):
errorMsg = 'Invalid or expired session id: %s.' % sessionId
logger.debug(errorMsg)
raise DmHttpError(dmHttpStatus.DM_HTTP_UNAUTHORIZED, 'User Not Authorized', AuthorizationError(errorMsg))
username = cherrypy.session.get(SESSION_USERNAME_KEY)
logger.debug('Session id %s is valid (username: %s)' % (sessionId, username))
if username:
cherrypy.request.login = username
for condition in conditions:
# A condition is just a callable that returns true or false
if not condition():
logger.debug('Authorization check %s failed for username %s' % (condition.func_name, username))
errorMsg = 'Authorization check %s failed for user %s.' % (condition.func_name, username)
raise DmHttpError(dmHttpStatus.DM_HTTP_UNAUTHORIZED, 'User Not Authorized', AuthorizationError(errorMsg))
else:
logger.debug('Username is not supplied')
raise DmHttpError(dmHttpStatus.DM_HTTP_UNAUTHORIZED, 'User Not Authorized', ex)
# Add before_handler for authorization
cherrypy.tools.auth = cherrypy.Tool('before_handler', checkAuth)
#cherrypy.tools.auth = cherrypy.Tool('on_start_resource', checkAuth)
def require(*conditions):
"""
A decorator that appends conditions to the auth.require config variable.
"""
def decorate(f):
if not hasattr(f, '_cp_config'):
f._cp_config = dict()
if 'auth.require' not in f._cp_config:
f._cp_config['auth.require'] = []
f._cp_config['auth.require'].extend(conditions)
return f
return decorate
# Conditions are callables that return True if the user
# fulfills the conditions they define, False otherwise.
# They can access the current username as cherrypy.request.login
def isAdminRole():
return (cherrypy.session.get(SESSION_ROLE_KEY, None) == dmRole.DM_ADMIN_ROLE)
def isUserOrAdminRole():
role = cherrypy.session.get(SESSION_ROLE_KEY, None)
if role == dmRole.DM_ADMIN_ROLE or role == dmRole.DM_USER_ROLE:
return True
return False
def isUser(username):
result = (cherrypy.session.get(SESSION_USERNAME_KEY, None) == username)
return result
def getSessionUser():
return cherrypy.session.get(SESSION_USERNAME_KEY, None)
def memberOf(groupname):
return cherrypy.request.login == 'dm' and groupname == 'admin'
def nameIs(reqd_username):
return lambda: reqd_username == cherrypy.request.login
def anyOf(*conditions):
""" Returns True if any of the conditions match. """
def check():
for c in conditions:
if c():
return True
return False
return check
def allOf(*conditions):
""" Returns True if all of the conditions match. """
def check():
for c in conditions:
if not c():
return False
return True
return check
class AuthController(DmController):
""" Controller to provide login and logout actions. """
_cp_config = {
'tools.sessions.on' : True,
'tools.sessions.storage_type' : 'dm',
'tools.auth.on' : True
}
def __init__(self):
DmController.__init__(self)
def onLogin(self, username):
""" Called on successful login. """
return
def onLogout(self, username):
""" Called on logout. """
return
@cherrypy.expose
def login(self, username=None, password=None, fromPage='/'):
logger = loggingManager.getLogger('login')
try:
if username is None or password is None:
(username, password) = parseBasicAuthorizationHeaders()
principal = checkCredentials(username, password)
except DmHttpError, ex:
raise
except DmException, ex:
logger.debug('Authorization failed (username %s): %s' % (username, ex))
self.addDmExceptionHeaders(ex)
raise DmHttpError(dmHttpStatus.DM_HTTP_UNAUTHORIZED, 'User Not Authorized', ex)
# Authorization worked.
cherrypy.session[SESSION_USERNAME_KEY] = cherrypy.request.login = username
self.onLogin(username)
self.addDmSessionRoleHeaders(principal.getRole())
self.addDmResponseHeaders()
@cherrypy.expose
def logout(self, fromPage='/'):
sess = cherrypy.session
username = sess.get(SESSION_USERNAME_KEY, None)
if username:
del sess[SESSION_USERNAME_KEY]
cherrypy.request.login = None
self.onLogout(username)
#!/usr/bin/env python
#
# Base DM controller class.
#
#######################################################################
import cherrypy
import httplib
from sys import exc_info
from dm.common.utility import loggingManager
from dm.common.constants import dmStatus
from dm.common.constants import dmHttpHeaders
from dm.common.exceptions.dmException import DmException
from dm.common.exceptions import dmExceptionMap
from dm.common.exceptions.internalError import InternalError
#######################################################################
class DmController(object):
""" Base controller class. """
def __init__(self):
self._logger = loggingManager.getLogger(self.__class__.__name__)
def getLogger(self):
return self._logger
@classmethod
def addDmResponseHeaders(cls, status=dmStatus.DM_OK, msg='Success', exceptionType=None):
cherrypy.response.headers[dmHttpHeaders.DM_STATUS_CODE_HTTP_HEADER] = status
cherrypy.response.headers[dmHttpHeaders.DM_STATUS_MESSAGE_HTTP_HEADER] = msg
if exceptionType is not None:
cherrypy.response.headers[dmHttpHeaders.DM_EXCEPTION_TYPE_HTTP_HEADER] = exceptionType
@classmethod
def addDmSessionRoleHeaders(cls, role):
cherrypy.response.headers[dmHttpHeaders.DM_SESSION_ROLE_HTTP_HEADER] = role
@classmethod
def addDmExceptionHeaders(cls, ex):
cls.handleException(ex)
@classmethod
def handleCpException(cls):
cherrypy.response.status = httplib.OK
ex = exc_info()[1]
if ex == None:
ex = InternalError('Internal Webservice Error')
cls.handleException(ex)
@classmethod
def handleException(cls, ex):
exClass = ex.__class__.__name__.split('.')[-1]
status = None
msg = '%s' % ex
msg = msg.split('\n')[0]
for code in dmExceptionMap.exceptionMap.keys():
exStr = dmExceptionMap.exceptionMap.get(code).split('.')[-1]
if exStr == exClass:
status = code
if not status:
status = dmStatus.DM_ERROR
cls.addDmResponseHeaders(status, msg, exClass)
def formatJsonResponse(self, response):
cherrypy.response.headers['Content-Type'] = 'application/json'
return '%s' % (response)
#!/usr/bin/env python
#
# Base web service class.
#
####################################################################
import sys
import cherrypy
from cherrypy.process import plugins
from cherrypy import server
from dm.common.constants import dmStatus
from dm.common.utility import configurationManager
from dm.common.utility import loggingManager
from dm.common.utility import dmModuleManager
####################################################################
class DmRestWebService:
DEFAULT_N_SERVER_REQUEST_THREADS = 10
DEFAULT_SERVER_SOCKET_TIMEOUT = 30
class SignalHandler:
def __init__(self, signal, oldSignalHandler):
self._signal = signal
self._oldSignalHandler = oldSignalHandler
self._logger = loggingManager.getInstance().getLogger(self.__class__.__name__)
def signalHandler(self):
self._logger.debug('%s signal handler called' % self._signal)
dmModuleManager.getInstance().stopModules()
self._oldSignalHandler()
def __init__(self, routeMapper):
self._configurationManager = configurationManager.getInstance()
self._routeMapper = routeMapper
self._options = None
self._args = None
self._logger = loggingManager.getInstance().getLogger(self.__class__.__name__)
self._logger.info('Initializing service')
def prepareOptions(self):
from optparse import OptionParser
p = OptionParser()
p.add_option('-d', '--daemon', action="store_true",
dest='daemonFlag', default=False,
help="Run as a daemon.")
p.add_option('-p', '--pidfile',
dest='pidfile', default=None,
help="Store the process id in the given file.")
p.add_option('-P', '--port',
dest='serverPort', default=self.getDefaultServerPort(),
help="Server port.")
p.add_option('-H', '--host',
dest='serverHost', default=self.getDefaultServerHost(),
help="Server host.")
p.add_option('-C', '--ssl-ca-cert',
dest='sslCaCert', default=None,
help='SSL CA certificate path (used for client SSL certificate verification). Requires --ssl-key and --ssl-cert.')
p.add_option('-c', '--ssl-cert',
dest='sslCert', default=None,
help='SSL certificate path. SSL operation requires both --ssl-key and --ssl-cert. Client SSL certificate verification also requires --ssl-ca-cert.')
p.add_option('-k', '--ssl-key',
dest='sslKey', default=None,
help='SSL key path. SSL operation requires both --ssl-key and --ssl-cert. Client SSL certificate verification also requires --ssl-ca-cert.')
p.add_option('', '--n-server-threads',
dest='nServerThreads', default=DmRestWebService.DEFAULT_N_SERVER_REQUEST_THREADS,
help='Number of service request handler threads (defaut: %s).' % DmRestWebService.DEFAULT_N_SERVER_REQUEST_THREADS)
return p
def initDmModules(self):
pass
def getDefaultServerHost(self):
return None
def getDefaultServerPort(self):
return None
# Instantiate modified signal handler that stops dm modules first,
# and then does the default action.
def modifySignalHandlers(self, engine):
pluginsSignalHandler = plugins.SignalHandler(engine)
handlers = pluginsSignalHandler.handlers
# Add handler for interrupt
handlers['SIGINT'] = engine.exit
# Modify all signal handlers
for signal in handlers.keys():
self._logger.debug('Modifying signal: %s' % signal)
oldSignalHandler = handlers[signal]
self._logger.debug('Old signal handler: %s' % oldSignalHandler)
signalHandler = DmRestWebService.SignalHandler(signal, oldSignalHandler)
self._logger.debug('Setting signal handler to: %s' % signalHandler.signalHandler)
handlers[signal] = signalHandler.signalHandler
pluginsSignalHandler.subscribe()
def initServerLog(self):
cherrypyLogLevel = self._configurationManager.getCherrypyLogLevel()
cherrypy.log.error_log.setLevel(cherrypyLogLevel)
cherrypy.log.error_file = self._configurationManager.getCherrypyLogFile()
cherrypy.log.error_log.propagate = False
cherrypy.log.access_log.setLevel(cherrypyLogLevel)
cherrypy.log.access_file = self._configurationManager.getCherrypyAccessFile()
cherrypy.log.access_log.propagate = False
def updateServerConfig(self):
configDict = {
'server.socket_host' : self._options.serverHost,
'server.socket_port' : int(self._options.serverPort),
'server.thread_pool' : int(self._options.nServerThreads),
'log.screen' : (self._options.daemonFlag != True),
}
cherrypy.config.update(configDict)
def prepareServer(self):
self._logger.debug('Preparing service configuration')
try:
optionParser = self.prepareOptions()
(self._options, self._args) = optionParser.parse_args()
dispatch = self._routeMapper.setupRoutes()
self._logger.debug('Using route dispatch: %s' % dispatch)
config = {
'/' : {
'request.dispatch' : dispatch,
},
}
# No root controller as we provided our own.
cherrypy.tree.mount(root=None, config=config)
self.initServerLog()
self.updateServerConfig()
self._logger.info('Using host %s' % self._options.serverHost)
self._logger.info('Using port %s' % self._options.serverPort)
self._logger.debug('Using %s request handler threads' % self._options.nServerThreads)
except Exception, ex:
self._logger.exception(ex)
sys.exit(dmStatus.DM_ERROR)
# Run server.
def __runServer(self):
self._logger.info('Starting service')
engine = cherrypy.engine
# Set up Deamonization
if self._options.daemonFlag:
plugins.Daemonizer(engine).subscribe()
self._logger.debug('Daemon mode: %s' % self._options.daemonFlag)
if self._options.pidfile != None:
plugins.PIDFile(engine, self._options.pidfile).subscribe()
self._logger.debug('Using PID file: %s' % self._options.pidfile)
if self._options.sslCert != None and self._options.sslKey != None:
server.ssl_ca_certificate = None
if self._options.sslCaCert != None:
server.ssl_ca_certificate = self._options.sslCaCert
self._configurationManager.setSslCaCertFile(self._options.sslCaCert)
self._logger.info('Using SSL CA cert file: %s' % self._options.sslCaCert)
server.ssl_certificate = self._options.sslCert
self._configurationManager.setSslCertFile(self._options.sslCert)
self._logger.info('Using SSL cert file: %s' % self._options.sslCert)
server.ssl_private_key = self._options.sslKey
self._configurationManager.setSslKeyFile(self._options.sslKey)
self._logger.info('Using SSL key file: %s' % self._options.sslKey)
server.ssl_module = 'builtin'
#server.ssl_module = 'pyopenssl'
# Increase timeout to prevent early SSL connection terminations
server.socket_timeout = DmRestWebService.DEFAULT_SERVER_SOCKET_TIMEOUT
# Setup the signal handler to stop the application while running.
if hasattr(engine, 'signal_handler'):
engine.signal_handler.subscribe()
if hasattr(engine, 'console_control_handler'):
engine.console_control_handler.subscribe()
self.modifySignalHandlers(engine)
# Turn off autoreloader.
self._logger.debug('Turning off autoreloader')
engine.autoreload.unsubscribe()
# Start the engine.
try:
self._logger.debug('Starting engine')
engine.start()
# Prepare dm services.
# Doing this before engine starts may cause issues with existing timers.
self._logger.debug('Starting modules')
self.initDmModules()
dmModuleManager.getInstance().startModules()
except Exception, ex:
self._logger.exception('Service exiting: %s' % ex)
dmModuleManager.getInstance().stopModules()
return dmStatus.DM_ERROR
self._logger.info('Service ready')
engine.block()
dmModuleManager.getInstance().stopModules()
self._logger.info('Service done')
return dmStatus.DM_OK
# Run server instance.
def run(self):
self.prepareOptions()
self.prepareServer()
sys.exit(self.__runServer())
####################################################################
# Testing
if __name__ == '__main__':
pass
This diff is collapsed.
#!/usr/bin/env python
#
# Console logging handler class
#
#######################################################################
import socket
import pwd
import os
from logging import StreamHandler
#######################################################################
class ConsoleLoggingHandler(StreamHandler):
""" Class that enables console logging. """
def __init__(self, *args):
StreamHandler.__init__(self, *args)
self._user = pwd.getpwuid(os.getuid())[0]
self._host = socket.gethostname()
def emit(self, record):
record.__dict__['user'] = self._user
record.__dict__['host'] = self._host
return StreamHandler.emit(self, record)
#######################################################################
# Testing.
if __name__ == '__main__':
import sys
import logging
exec 'sh = ConsoleLoggingHandler(sys.stdout,)'
sh.setLevel(logging.INFO)
rootLogger = logging.getLogger('')
logging.basicConfig(level=logging.DEBUG)
mainLogger = logging.getLogger('main')
mainLogger.debug("main debug")
mainLogger.info("main info")
#!/usr/bin/env python
#
# Module manager class.
#
#######################################################################
import threading
#######################################################################
# Get singleton instance.
def getInstance():
from dm.common.utility.dmModuleManager import DmModuleManager
try:
mgr = DmModuleManager()
except DmModuleManager, ex:
mgr = ex
return mgr
class DmModuleManager:
""" Singleton class used for managing dm modules. """
# Singleton.
__instanceLock = threading.RLock()
__instance = None
def __init__(self):
DmModuleManager.__instanceLock.acquire()
try:
if DmModuleManager.__instance:
raise DmModuleManager.__instance
DmModuleManager.__instance = self
from dm.common.utility import loggingManager
self._logger = loggingManager.getLogger(self.__class__.__name__)
self._lock = threading.RLock()
self._moduleList = []
self._modulesRunning = False
finally:
DmModuleManager.__instanceLock.release()
def addModule(self, m):
self._lock.acquire()
try:
self._logger.debug('Adding dm module: %s' % m.__class__.__name__)
self._moduleList.append(m)
finally:
self._lock.release()
def startModules(self):
self._lock.acquire()
try:
if self._modulesRunning:
return
for m in self._moduleList:
self._logger.debug('Starting dm module: %s' % m.__class__.__name__)
m.start()
self._modulesRunning = True
finally:
self._lock.release()
def stopModules(self):
self._lock.acquire()
try:
if not self._modulesRunning:
return
n = len(self._moduleList)
for i in range(0, n):
m = self._moduleList[n-1-i]
self._logger.debug('Stopping dm module: %s' % m.__class__.__name__)
m.stop()
self._modulesRunning = False
finally:
self._lock.release()
#######################################################################
# Testing.
if __name__ == '__main__':
pass