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

# Source Code for Module Products.ZenUtils.ZenScriptBase

      1  ###########################################################################
      2  #
      3  # This program is part of Zenoss Core, an open source monitoring platform.
      4  # Copyright (C) 2007, Zenoss Inc.
      5  #
      6  # This program is free software; you can redistribute it and/or modify it
      7  # under the terms of the GNU General Public License version 2 or (at your
      8  # option) any later version as published by the Free Software Foundation.
      9  #
     10  # For complete information please visit: http://www.zenoss.com/oss/
     11  #
     12  ###########################################################################
     13
     14  __doc__="""ZenScriptBase
     15  """
     16
     17  from AccessControl.SecurityManagement import newSecurityManager
     18  from AccessControl.SecurityManagement import noSecurityManager
     19  from transaction import commit
     20  from Utils import getObjByPath, zenPath, set_context
     21  from Products.ZenUtils.CmdBase import CmdBase
     22  from Products.ZenUtils.ZCmdBase import ZCmdBase
     23
     24  from Products.Five import zcml
     25
     26  from Products.ZenRelations.ZenPropertyManager import setDescriptors
     27  from Exceptions import ZentinelException
     28
     29  defaultCacheDir = zenPath('var')
     30
     31 -class DataRootError(Exception):pass
     32
     33 -class ZenScriptBase(CmdBase):
     34
     35 -    def __init__(self, noopts=0, app=None, connect=False):
     36          import Products.ZenossStartup
     37          zcml.load_site()
     38          CmdBase.__init__(self, noopts)
     39          self.dataroot = None
     40          self.app = app
     41          self.db = None
     42          if connect:
     43              self.connect()
     44
     45 -    def connect(self):
     46          if not self.app:
     47              self.options.port = self.options.port or 3306
     48              from relstorage.storage import RelStorage
     49              from relstorage.adapters.mysql import MySQLAdapter
     50              connectionParams = {
     51                  'host' : self.options.host,
     52                  'port' : self.options.port,
     53                  'user' : self.options.mysqluser,
     54                  'passwd' : self.options.mysqlpasswd,
     55                  'db' : self.options.mysqldb,
     56              }
     57              if getattr(self.options, 'mysqlsocket', None) and self.options.mysqlsocket != 'None':
     58                  connectionParams['unix_socket'] = self.options.mysqlsocket
     59
     60              kwargs = {
     61                  'cache_module_name':'memcache',
     62                  'keep_history': False,
     63              }
     64              from relstorage.options import Options
     65              adapter = MySQLAdapter(options=Options(**kwargs), **connectionParams)
     66
     67              if self.options.cacheservers:
     68                  kwargs['cache_servers'] = self.options.cacheservers
     69              self.storage = RelStorage(adapter, **kwargs)
     70              from ZODB import DB
     71              self.db = DB(self.storage, cache_size=self.options.cachesize)
     72          self.getDataRoot()
     73          self.login()
     74          if getattr(self.dmd, 'propertyTransformers', None) is None:
     75              self.dmd.propertyTransformers = {}
     76              commit()
     77          setDescriptors(self.dmd.propertyTransformers)
     78
     79
     80 -    def login(self, name='admin', userfolder=None):
     81          '''Logs in.'''
     82          if userfolder is None:
     83              userfolder = self.app.acl_users
     84          user = userfolder.getUserById(name)
     85          if user is None: return
     86          if not hasattr(user, 'aq_base'):
     87              user = user.__of__(userfolder)
     88          newSecurityManager(None, user)
     89
     90
     91 -    def logout(self):
     92          '''Logs out.'''
     93          noSecurityManager()
     94
     95
     96 -    def getConnection(self):
     97          """Return a wrapped app connection from the connection pool.
     98          """
     99          if not self.db:
    100              raise ZentinelException(
    101                  "running inside zope can't open connections.")
    102          with self.poollock:
    103              connection=self.db.open()
    104              root=connection.root()
    105              app=root['Application']
    106              app = set_context(app)
    107              app._p_jar.sync()
    108              return app
    109
    110
    111 -    def closeAll(self):
    112          """Close all connections in both free an inuse pools.
    113          """
    114          self.db.close()
    115
    116
    117 -    def opendb(self):
    118          if self.app: return
    119          self.connection=self.db.open()
    120          root=self.connection.root()
    121          app = root['Application']
    122          self.app = set_context(app)
    123          self.app._p_jar.sync()
    124
    125
    126 -    def syncdb(self):
    127          self.connection.sync()
    128
    129
    130 -    def closedb(self):
    131          self.connection.close()
    132          #self.db.close()
    133          self.app = None
    134          self.dataroot = None
    135          self.dmd = None
    136
    137
    138 -    def getDataRoot(self):
    139          if not self.app: self.opendb()
    140          if not self.dataroot:
    141              self.dataroot = getObjByPath(self.app, self.options.dataroot)
    142              self.dmd = self.dataroot
    143
    144
    145 -    def getDmdObj(self, path):
    146          """return an object based on a path starting from the dmd"""
    147          return getObjByPath(self.app, self.options.dataroot+path)
    148
    149
    150 -    def findDevice(self, name):
    151          """return a device based on its FQDN"""
    152          devices = self.dataroot.getDmdRoot("Devices")
    153          return devices.findDevice(name)
    154
    155
    156 -    def buildOptions(self):
    157          """basic options setup sub classes can add more options here"""
    158          CmdBase.buildOptions(self)
    159          self.parser.add_option('-R', '--dataroot',
    160                      dest="dataroot",
    161                      default="/zport/dmd",
    162                      help="root object for data load (i.e. /zport/dmd)")
    163          self.parser.add_option('--cachesize',
    164                      dest="cachesize",default=1000, type='int',
    165                      help="in memory cachesize default: 1000")
    166          self.parser.add_option('--host',
    167                      dest="host",default="localhost",
    168                      help="hostname of MySQL object store")
    169          self.parser.add_option('--port',
    170                      dest="port", type="int", default=3306,
    171                      help="port of MySQL object store")
    172          self.parser.add_option('--mysqluser', dest='mysqluser', default='zenoss',
    173                      help='username for MySQL object store')
    174          self.parser.add_option('--mysqlpasswd', dest='mysqlpasswd', default='zenoss',
    175                      help='passwd for MySQL object store')
    176          self.parser.add_option('--mysqldb', dest='mysqldb', default='zodb',
    177                      help='Name of database for MySQL object store')
    178          self.parser.add_option('--mysqlsocket', dest='mysqlsocket', default=None,
    179                      help='Name of socket file for MySQL server connection')
    180          self.parser.add_option('--cacheservers', dest='cacheservers', default="",
    181                      help='memcached servers to use for object cache (eg. 127.0.0.1:11211)')
    182