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 as published by
      8  # 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 threading import Lock
     20  from transaction import commit
     21  from Utils import getObjByPath, zenPath, set_context
     22  from CmdBase import CmdBase
     23
     24  from Products.ZenRelations.ZenPropertyManager import setDescriptors
     25  from Exceptions import ZentinelException
     26
     27  defaultCacheDir = zenPath('var')
     28
     29 -class DataRootError(Exception):pass
     30
     31 -class ZenScriptBase(CmdBase):
     32
     33 -    def __init__(self, noopts=0, app=None, connect=False):
     34          CmdBase.__init__(self, noopts)
     35          self.dataroot = None
     36          self.app = app
     37          self.db = None
     38          if connect:
     39              self.connect()
     40
     41
     42 -    def connect(self):
     43          if not self.app:
     44              from ZEO import ClientStorage
     45              from ZODB import DB
     46              addr = (self.options.host, self.options.port)
     47              storage=ClientStorage.ClientStorage(addr,
     48                              client=self.options.pcachename,
     49                              var=self.options.pcachedir,
     50                              cache_size=self.options.pcachesize*1024*1024)
     51              self.db=DB(storage, cache_size=self.options.cachesize)
     52              self.poollock = Lock()
     53          self.getDataRoot()
     54          self.login()
     55          if not getattr(self.dmd, 'propertyTransformers', None):
     56              self.dmd.propertyTransformers = {}
     57              commit()
     58          setDescriptors(self.dmd.propertyTransformers)
     59
     60
     61 -    def login(self, name='admin', userfolder=None):
     62          '''Logs in.'''
     63          if userfolder is None:
     64              userfolder = self.app.acl_users
     65          user = userfolder.getUserById(name)
     66          if user is None: return
     67          if not hasattr(user, 'aq_base'):
     68              user = user.__of__(userfolder)
     69          newSecurityManager(None, user)
     70
     71
     72 -    def logout(self):
     73          '''Logs out.'''
     74          noSecurityManager()
     75
     76
     77 -    def getConnection(self):
     78          """Return a wrapped app connection from the connection pool.
     79          """
     80          if not self.db:
     81              raise ZentinelException(
     82                  "running inside zope can't open connections.")
     83          try:
     84              self.poollock.acquire()
     85              connection=self.db.open()
     86              root=connection.root()
     87              app=root['Application']
     88              app = set_context(app)
     89              app._p_jar.sync()
     90              return app
     91          finally:
     92              self.poollock.release()
     93
     94
     95 -    def closeAll(self):
     96          """Close all connections in both free an inuse pools.
     97          """
     98          self.db.close()
     99
    100
    101 -    def opendb(self):
    102          if self.app: return
    103          self.connection=self.db.open()
    104          root=self.connection.root()
    105          app = root['Application']
    106          self.app = set_context(app)
    107          self.app._p_jar.sync()
    108
    109
    110 -    def syncdb(self):
    111          self.connection.sync()
    112
    113
    114 -    def closedb(self):
    115          self.connection.close()
    116          #self.db.close()
    117          self.app = None
    118          self.dataroot = None
    119          self.dmd = None
    120
    121
    122 -    def getDataRoot(self):
    123          if not self.app: self.opendb()
    124          if not self.dataroot:
    125              self.dataroot = getObjByPath(self.app, self.options.dataroot)
    126              self.dmd = self.dataroot
    127
    128
    129 -    def getDmdObj(self, path):
    130          """return an object based on a path starting from the dmd"""
    131          return getObjByPath(self.app, self.options.dataroot+path)
    132
    133
    134 -    def findDevice(self, name):
    135          """return a device based on its FQDN"""
    136          devices = self.dataroot.getDmdRoot("Devices")
    137          return devices.findDevice(name)
    138
    139
    140 -    def buildOptions(self):
    141          """basic options setup sub classes can add more options here"""
    142          CmdBase.buildOptions(self)
    143          self.parser.add_option('--host',
    144                      dest="host",default="localhost",
    145                      help="hostname of zeo server")
    146          self.parser.add_option('--port',
    147                      dest="port",type="int", default=8100,
    148                      help="port of zeo server")
    149          self.parser.add_option('-R', '--dataroot',
    150                      dest="dataroot",
    151                      default="/zport/dmd",
    152                      help="root object for data load (i.e. /zport/dmd)")
    153          self.parser.add_option('--cachesize',
    154                      dest="cachesize",default=1000, type='int',
    155                      help="in memory cachesize default: 1000")
    156          self.parser.add_option('--pcachename',
    157                      dest="pcachename",default=None,
    158                      help="persistent cache file name default:None")
    159          self.parser.add_option('--pcachedir',
    160                      dest="pcachedir",default=defaultCacheDir,
    161                      help="persistent cache file directory")
    162          self.parser.add_option('--pcachesize',
    163                      dest="pcachesize",default=10, type='int',
    164                      help="persistent cache file size in MB")
    165