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

# Source Code for Module Products.ZenUtils.PostgresqlZodbFactory

      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__="""PostgresqlZodbFactory
     12  """
     13
     14  import logging
     15  log = logging.getLogger("zen.PostgresqlZodbFactory")
     16
     17  import optparse
     18  from zope.interface import implements
     19  import ZODB
     20  import relstorage.storage
     21  import relstorage.adapters.postgresql
     22  import relstorage.options
     23
     24  import psycopg2 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', 5432),
     37          'user': o.get('zodb-user', 'zenoss'),
     38          'password': o.get('zodb-password', 'zenoss'),
     39          'dbname': o.get('zodb-db', 'zodb'),
     40      }
     41      if 'zodb-socket' in o:
     42          settings['socket'] = o['zodb-socket']
     43      return settings
     44
     45
     46 -class PostgresqlZodbFactory(object):
     47      implements(IZodbFactory)
     48
     49      # set db specific here to allow more flexible imports
     50      exceptions = db_exceptions
     51
     52
     53 -    def getZopeZodbConf(self):
     54          """Return a zope.conf style zodb config."""
     55          settings = _getDefaults()
     56          dsn = []
     57          keys = ['host', 'port', 'socket', 'user', 'password', 'dbname']
     58          for key in keys:
     59              if key in settings:
     60                  dsn.append("%s=%s" % (key, settings[key],))
     61
     62          stanza = "\n".join([
     63              "<postgresql>",
     64              "    dsn %s" % (" ".join(dsn),),
     65              "</postgresql>\n",
     66          ])
     67          return stanza
     68
     69 -    def getConnection(self, **kwargs):
     70          """Return a ZODB connection."""
     71          connectionParams =  _getDefaults(kwargs)
     72          kwargs = {
     73              'cache_module_name':'memcache',
     74              'keep_history': kwargs.get('zodb_keep_history', False)
     75          }
     76          adapter = relstorage.adapters.postgresql.PostgreSQLAdapter(
     77               dsn="dbname=%(dbname)s port=%(port)s user=%(user)s password=%(password)s" % connectionParams,
     78               options=relstorage.options.Options(**kwargs))
     79
     80          # rename the poll_interval and cache_servers options to not
     81          # have the zodb prefix.
     82          if 'zodb_poll_interval' in kwargs:
     83              kwargs['poll_interval'] = kwargs['zodb_poll_interval']
     84          if 'zodb_cacheservers' in kwargs:
     85              kwargs['cache_servers'] = kwargs['zodb_cacheservers']
     86
     87          if 'poll_interval' in kwargs:
     88              poll_interval = kwargs['poll_interval']
     89              if 'cache_servers' in kwargs:
     90                  if poll_interval is None:
     91                      log.info("Using default poll-interval of 60 seconds because "
     92                               "cache-servers was set.")
     93                      kwargs['poll_interval'] = 60
     94                  else:
     95                      kwargs['poll_interval'] = poll_interval
     96              else:
     97                  log.warn("poll-interval of %r is being ignored because "
     98                           "cache-servers was not set." % poll_interval)
     99          storage = relstorage.storage.RelStorage(adapter, **kwargs)
    100          cache_size = kwargs.get('zodb_cachesize', 1000)
    101          db = ZODB.DB(storage, cache_size=cache_size)
    102          return db, storage
    103
    104 -    def buildOptions(self, parser):
    105          """build OptParse options for ZODB connections"""
    106          group = optparse.OptionGroup(parser, "ZODB Options",
    107              "ZODB connection options and PostgreSQL Adapter options.")
    108          group.add_option('-R', '--zodb-dataroot',
    109                      dest="dataroot",
    110                      default="/zport/dmd",
    111                      help="root object for data load (i.e. /zport/dmd)")
    112          group.add_option('--zodb-cachesize',
    113                      dest="zodb_cachesize",default=1000, type='int',
    114                      help="in memory cachesize default: 1000")
    115          group.add_option('--zodb-host',
    116                      dest="zodb_host",default="localhost",
    117                      help="hostname of the PostgreSQL server for ZODB")
    118          group.add_option('--zodb-port',
    119                      dest="zodb_port", type="int", default=5432,
    120                      help="port of the PostgreSQL server for ZODB")
    121          group.add_option('--zodb-user', dest='zodb_user', default='zenoss',
    122                      help='user of the PostgreSQL server for ZODB')
    123          group.add_option('--zodb-password', dest='zodb_password', default='zenoss',
    124                      help='password of the PostgreSQL server for ZODB')
    125          group.add_option('--zodb-db', dest='zodb_db', default='zodb',
    126                      help='Name of database for PostgreSQL object store')
    127          # TODO: implement passing socket option to PostgreSQL adapter
    128          group.add_option('--zodb-socket', dest='zodb_socket', default=None,
    129                      help='Name of socket file for PostgreSQL server connection if host is localhost')
    130          group.add_option('--zodb-cacheservers', dest='zodb_cacheservers', default="",
    131                      help='memcached servers to use for object cache (eg. 127.0.0.1:11211)')
    132          group.add_option('--zodb-poll-interval', dest='zodb_poll_interval', default=None, type='int',
    133                      help='Defer polling the database for the specified maximum time interval, in seconds.'
    134                      ' This will default to 60 only if --zodb-cacheservers is set.')
    135          parser.add_option_group(group)
    136