Package Products :: Package ZenUtils :: Module MySqlZodbFactory |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenUtils.MySqlZodbFactory

      1  ##############################################################################
      2  #
      3  # Copyright (C) Zenoss, Inc. 2011, all rights reserved.
      4  #
      5  # This content is made available according to terms specified in
      6  # License.zenoss under the directory where your Zenoss product is installed.
      7  #
      8  ##############################################################################
      9
     10
     11  __doc__="""MySqlZodbConnection
     12  """
     13
     14  import logging
     15  log = logging.getLogger("zen.MySqlZodbFactory")
     16
     17  import optparse
     18  import os
     19  from zope.interface import implements
     20  import ZODB
     21  import relstorage.storage
     22  import relstorage.adapters.mysql
     23  import relstorage.options
     24  import _mysql_exceptions as db_exceptions
     25
     26  from Products.ZenUtils.GlobalConfig import globalConfToDict
     27  from Products.ZenUtils.ZodbFactory import IZodbFactory
     28
     29 -def _getDefaults(options=None):
     30      if options is None:
     31         o = globalConfToDict()
     32      else:
     33         o = options
     34      settings = {
     35          'host': o.get('zodb-host', "localhost"),
     36          'port': o.get('zodb-port', 3306),
     37          'user': o.get('zodb-user', 'zenoss'),
     38          'passwd': o.get('zodb-password', 'zenoss'),
     39          'db': o.get('zodb-db', 'zodb'),
     40      }
     41      if 'zodb-socket' in o:
     42          settings['unix_socket'] = o['zodb-socket']
     43      return settings
     44
     45
     46
     47 -class MySqlZodbFactory(object):
     48      implements(IZodbFactory)
     49
     50      # set db specific here to allow more flexible imports
     51      exceptions = db_exceptions
     52
     53 -    def _getConf(self, settings):
     54          config = []
     55          keys = ['host', 'port', 'unix_socket', 'user', 'passwd', 'db']
     56          for key in keys:
     57              if key in settings:
     58                  config.append("    %s %s" % (key, settings[key],))
     59
     60          stanza = "\n".join([
     61              "<mysql>",
     62              "\n".join(config),
     63              "</mysql>\n",
     64          ])
     65          return stanza
     66
     67 -    def getZopeZodbConf(self):
     68          """Return a zope.conf style zodb config."""
     69          settings = _getDefaults()
     70          return self._getConf(settings)
     71
     72 -    def getZopeZodbSessionConf(self):
     73          """Return a zope.conf style zodb config."""
     74          settings = _getDefaults()
     75          settings['db'] += '_session'
     76          return self._getConf(settings)
     77
     78 -    def getConnection(self, **kwargs):
     79          """Return a ZODB connection."""
     80          connectionParams = {
     81              'host': kwargs.get('zodb_host', "localhost"),
     82              'port': kwargs.get('zodb_port', 3306),
     83              'user': kwargs.get('zodb_user', 'zenoss'),
     84              'passwd': kwargs.get('zodb_password', 'zenoss'),
     85              'db': kwargs.get('zodb_db',  'zodb'),
     86          }
     87          socket = kwargs.get('zodb_socket')
     88          if not socket:
     89              # try to auto set ZENDS socket
     90              use_zends = os.environ.get("USE_ZENDS", False)
     91              if use_zends and use_zends == "1":
     92                  zends_home = os.environ.get("ZENDSHOME", "")
     93                  zends_socket = os.path.join(zends_home, "data", "zends.sock")
     94                  if zends_home and os.path.exists(zends_socket):
     95                      socket = zends_socket
     96          if socket:
     97              connectionParams['unix_socket'] = socket
     98          kwargs = {
     99              'cache_module_name':'memcache',
    100              'keep_history': kwargs.get('zodb_keep_history', False)
    101          }
    102          adapter = relstorage.adapters.mysql.MySQLAdapter(
    103               options=relstorage.options.Options(**kwargs),
    104               **connectionParams)
    105
    106          # rename the poll_interval and cache_servers options to not
    107          # have the zodb prefix.
    108          if 'zodb_poll_interval' in kwargs:
    109              kwargs['poll_interval'] = kwargs['zodb_poll_interval']
    110          if 'zodb_cacheservers' in kwargs:
    111              kwargs['cache_servers'] = kwargs['zodb_cacheservers']
    112
    113          if 'poll_interval' in kwargs:
    114              poll_interval = kwargs['poll_interval']
    115              if 'cache_servers' in kwargs:
    116                  if poll_interval is None:
    117                      log.info("Using default poll-interval of 60 seconds because "
    118                               "cache-servers was set.")
    119                      kwargs['poll_interval'] = 60
    120                  else:
    121                      kwargs['poll_interval'] = poll_interval
    122              else:
    123                  log.warn("poll-interval of %r is being ignored because "
    124                           "cache-servers was not set." % poll_interval)
    125          storage = relstorage.storage.RelStorage(adapter, **kwargs)
    126          cache_size = kwargs.get('zodb_cachesize', 1000)
    127          db = ZODB.DB(storage, cache_size=cache_size)
    128          import Globals
    129          Globals.DB = db
    130          return db, storage
    131
    132 -    def buildOptions(self, parser):
    133          """build OptParse options for ZODB connections"""
    134          group = optparse.OptionGroup(parser, "ZODB Options",
    135              "ZODB connection options and MySQL Adapter options.")
    136          group.add_option('-R', '--zodb-dataroot',
    137                      dest="dataroot",
    138                      default="/zport/dmd",
    139                      help="root object for data load (i.e. /zport/dmd)")
    140          group.add_option('--zodb-cachesize',
    141                      dest="zodb_cachesize",default=1000, type='int',
    142                      help="in memory cachesize default: 1000")
    143          group.add_option('--zodb-host',
    144                      dest="zodb_host",default="localhost",
    145                      help="hostname of the MySQL server for ZODB")
    146          group.add_option('--zodb-port',
    147                      dest="zodb_port", type="int", default=3306,
    148                      help="port of the MySQL server for ZODB")
    149          group.add_option('--zodb-user', dest='zodb_user', default='zenoss',
    150                      help='user of the MySQL server for ZODB')
    151          group.add_option('--zodb-password', dest='zodb_password', default='zenoss',
    152                      help='password of the MySQL server for ZODB')
    153          group.add_option('--zodb-db', dest='zodb_db', default='zodb',
    154                      help='Name of database for MySQL object store')
    155          group.add_option('--zodb-socket', dest='zodb_socket', default=None,
    156                      help='Name of socket file for MySQL server connection if host is localhost')
    157          group.add_option('--zodb-cacheservers', dest='zodb_cacheservers', default="",
    158                      help='memcached servers to use for object cache (eg. 127.0.0.1:11211)')
    159          group.add_option('--zodb-poll-interval', dest='zodb_poll_interval', default=None, type='int',
    160                      help='Defer polling the database for the specified maximum time interval, in seconds.'
    161                      ' This will default to 60 only if --zodb-cacheservers is set.')
    162          parser.add_option_group(group)
    163