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

# Source Code for Module Products.ZenUtils.ZCmdBase

      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__="""ZenDaemon
     15
     16  $Id: ZC.py,v 1.9 2004/02/16 17:19:31 edahl Exp $"""
     17
     18  __version__ = "$Revision: 1.9 $"[11:-2]
     19
     20  from threading import Lock
     21
     22  from AccessControl.SecurityManagement import newSecurityManager
     23  from AccessControl.SecurityManagement import noSecurityManager
     24  from Products.Five import zcml
     25
     26  from Utils import getObjByPath, zenPath
     27
     28  from Exceptions import ZentinelException
     29  from ZenDaemon import ZenDaemon
     30
     31  from Products.ZenRelations.ZenPropertyManager import setDescriptors
     32
     33  import os
     34  defaultCacheDir = zenPath('var')
     35
     36 -class DataRootError(Exception):pass
     37
     38 -def login(context, name='admin', userfolder=None):
     39      '''Logs in.'''
     40      if userfolder is None:
     41          userfolder = context.getPhysicalRoot().acl_users
     42      user = userfolder.getUserById(name)
     43      if user is None: return
     44      if not hasattr(user, 'aq_base'):
     45          user = user.__of__(userfolder)
     46      newSecurityManager(None, user)
     47      return user
     48
     49 -class ZCmdBase(ZenDaemon):
     50
     51 -    def __init__(self, noopts=0, app=None, keeproot=False):
     52          import Products.ZenossStartup
     53          zcml.load_site()
     54          ZenDaemon.__init__(self, noopts, keeproot)
     55          self.dataroot = None
     56          self.app = app
     57          self.db = None
     58          if not app:
     59              self.zodbConnect()
     60          self.poollock = Lock()
     61          self.getDataRoot()
     62          self.login()
     63          setDescriptors(self.dmd.propertyTransformers)
     64
     65 -    def zodbConnect(self):
     66          self.options.port = self.options.port or 3306
     67          from relstorage.storage import RelStorage
     68          from relstorage.adapters.mysql import MySQLAdapter
     69          connectionParams = {
     70              'host' : self.options.host,
     71              'port' : self.options.port,
     72              'user' : self.options.mysqluser,
     73              'passwd' : self.options.mysqlpasswd,
     74              'db' : self.options.mysqldb,
     75          }
     76          if getattr(self.options, 'mysqlsocket', None) and self.options.mysqlsocket != 'None':
     77              connectionParams['unix_socket'] = self.options.mysqlsocket
     78
     79          kwargs = {
     80              'cache_module_name':'memcache',
     81              'keep_history': False,
     82          }
     83          from relstorage.options import Options
     84          adapter = MySQLAdapter(options=Options(**kwargs),**connectionParams)
     85          if self.options.cacheservers:
     86              kwargs['cache_servers'] = self.options.cacheservers
     87          if self.options.pollinterval:
     88              if 'cache_servers' in kwargs:
     89                  if self.options.pollinterval is None:
     90                      self.log.info("Using default poll-interval of 60 seconds because "
     91                          "cache-servers was set.")
     92                      kwargs['poll_interval'] = 60
     93                  else:
     94                      kwargs['poll_interval'] = self.options.pollinterval
     95              else:
     96                  self.log.warn("poll-interval of %r is being ignored because "
     97                      "cache-servers was not set." % self.options.pollinterval)
     98          self.storage = RelStorage(adapter, **kwargs)
     99          from ZODB import DB
    100          self.db = DB(self.storage, cache_size=self.options.cachesize)
    101
    102
    103 -    def login(self, name='admin', userfolder=None):
    104          '''Logs in.'''
    105          login(self.dmd, name, userfolder)
    106
    107
    108 -    def logout(self):
    109          '''Logs out.'''
    110          noSecurityManager()
    111
    112
    113 -    def getConnection(self):
    114          """Return a wrapped app connection from the connection pool.
    115          """
    116          if not self.db:
    117              raise ZentinelException(
    118                  "running inside zope can't open connections.")
    119          with self.poollock:
    120              connection=self.db.open()
    121              root=connection.root()
    122              app=root['Application']
    123              app = self.getContext(app)
    124              app._p_jar.sync()
    125              return app
    126
    127
    128 -    def closeAll(self):
    129          """Close all connections in both free an inuse pools.
    130          """
    131          self.db.close()
    132
    133
    134 -    def opendb(self):
    135          if self.app: return
    136          self.connection=self.db.open()
    137          root=self.connection.root()
    138          app=root['Application']
    139          self.app = self.getContext(app)
    140
    141
    142 -    def syncdb(self):
    143          self.connection.sync()
    144
    145
    146 -    def closedb(self):
    147          self.connection.close()
    148          #self.db.close()
    149          self.app = None
    150          self.dataroot = None
    151          self.dmd = None
    152
    153
    154 -    def getDataRoot(self):
    155          if not self.app: self.opendb()
    156          if not self.dataroot:
    157              self.dataroot = getObjByPath(self.app, self.options.dataroot)
    158              self.dmd = self.dataroot
    159
    160
    161 -    def getContext(self, app):
    162          from ZPublisher.HTTPRequest import HTTPRequest
    163          from ZPublisher.HTTPResponse import HTTPResponse
    164          from ZPublisher.BaseRequest import RequestContainer
    165          resp = HTTPResponse(stdout=None)
    166          env = {
    167              'SERVER_NAME':'localhost',
    168              'SERVER_PORT':'8080',
    169              'REQUEST_METHOD':'GET'
    170              }
    171          req = HTTPRequest(None, env, resp)
    172          return app.__of__(RequestContainer(REQUEST = req))
    173
    174
    175 -    def getDmdObj(self, path):
    176          """return an object based on a path starting from the dmd"""
    177          return getObjByPath(self.app, self.options.dataroot+path)
    178
    179
    180 -    def findDevice(self, name):
    181          """return a device based on its FQDN"""
    182          devices = self.dataroot.getDmdRoot("Devices")
    183          return devices.findDevice(name)
    184
    185 -    def sigTerm(self, signum=None, frame=None):
    186          pass
    187
    188 -    def buildOptions(self):
    189          """basic options setup sub classes can add more options here"""
    190          ZenDaemon.buildOptions(self)
    191          self.parser.add_option('-R', '--dataroot',
    192                      dest="dataroot",
    193                      default="/zport/dmd",
    194                      help="root object for data load (i.e. /zport/dmd)")
    195          self.parser.add_option('--cachesize',
    196                      dest="cachesize",default=1000, type='int',
    197                      help="in memory cachesize default: 1000")
    198          self.parser.add_option('--host',
    199                      dest="host",default="localhost",
    200                      help="hostname of MySQL object store")
    201          self.parser.add_option('--port',
    202                      dest="port", type="int", default=3306,
    203                      help="port of MySQL object store")
    204          self.parser.add_option('--mysqluser', dest='mysqluser', default='zenoss',
    205                      help='username for MySQL object store')
    206          self.parser.add_option('--mysqlpasswd', dest='mysqlpasswd', default='zenoss',
    207                      help='passwd for MySQL object store')
    208          self.parser.add_option('--mysqldb', dest='mysqldb', default='zodb',
    209                      help='Name of database for MySQL object store')
    210          self.parser.add_option('--mysqlsocket', dest='mysqlsocket', default=None,
    211                      help='Name of socket file for MySQL server connection')
    212          self.parser.add_option('--cacheservers', dest='cacheservers', default="",
    213                      help='memcached servers to use for object cache (eg. 127.0.0.1:11211)')
    214          self.parser.add_option('--poll-interval', dest='pollinterval', default=None, type='int',
    215                      help='Defer polling the database for the specified maximum time interval, in seconds.'
    216                      ' This will default to 60 only if --cacheservers is set.')
    217