Package Products :: Package ZenModel :: Module ServiceOrganizer |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenModel.ServiceOrganizer

      1  ##############################################################################
      2  #
      3  # Copyright (C) Zenoss, Inc. 2007, 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  import logging
     12  log = logging.getLogger("zen.ServiceOrganizer")
     13
     14  from Globals import DTMLFile
     15  from Globals import InitializeClass
     16  from AccessControl import ClassSecurityInfo
     17  from AccessControl import Permissions
     18  from Products.ZenModel.ZenossSecurity import *
     19  from Acquisition import aq_base
     20  from Commandable import Commandable
     21  from ZenPackable import ZenPackable
     22
     23  from Products.ZenRelations.RelSchema import *
     24  from Products.ZenRelations.ZenPropertyManager import iszprop
     25
     26
     27  from Organizer import Organizer
     28  from ServiceClass import ServiceClass
     29  from IpServiceClass import IpServiceClass
     30
     31 -def manage_addServiceOrganizer(context, id, REQUEST = None):
     32      """make a device class"""
     33      sc = ServiceOrganizer(id)
     34      context._setObject(id, sc)
     35      sc = context._getOb(id)
     36      if REQUEST is not None:
     37          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     38
     39  addServiceOrganizer = DTMLFile('dtml/addServiceOrganizer',globals())
     40
     41 -class ServiceOrganizer(Organizer, Commandable, ZenPackable):
     42      meta_type = "ServiceOrganizer"
     43      dmdRootName = "Services"
     44      default_catalog = "serviceSearch"
     45
     46      description = ""
     47
     48      _properties = (
     49          {'id':'description', 'type':'text', 'mode':'w'},
     50          )
     51
     52      _relations = Organizer._relations + ZenPackable._relations + (
     53          ("serviceclasses", ToManyCont(ToOne,"Products.ZenModel.ServiceClass","serviceorganizer")),
     54          ('userCommands', ToManyCont(ToOne, 'Products.ZenModel.UserCommand', 'commandable')),
     55          )
     56
     57      factory_type_information = (
     58          {
     59              'id'             : 'ServiceOrganizer',
     60              'meta_type'      : 'ServiceOrganizer',
     61              'icon'           : 'ServiceOrganizer.gif',
     62              'product'        : 'ZenModel',
     63              'factory'        : 'manage_addServiceOrganizer',
     64              'immediate_view' : 'serviceOrganizerOverview',
     65              'actions'        :
     66              (
     67                  { 'id'            : 'classes'
     68                  , 'name'          : 'Classes'
     69                  , 'action'        : 'serviceOrganizerOverview'
     70                  , 'permissions'   : (
     71                    Permissions.view, )
     72                  },
     73                  { 'id'            : 'manage'
     74                  , 'name'          : 'Administration'
     75                  , 'action'        : 'serviceOrganizerManage'
     76                  , 'permissions'   : ("Manage DMD",)
     77                  },
     78                  { 'id'            : 'zproperties'
     79                  , 'name'          : 'Configuration Properties'
     80                  , 'action'        : 'zPropertyEdit'
     81                  , 'permissions'   : ("Change Device",)
     82                  },
     83              )
     84           },
     85          )
     86
     87      security = ClassSecurityInfo()
     88
     89 -    def __init__(self, id=None, description=None):
     90          if not id: id = self.dmdRootName
     91          super(ServiceOrganizer, self).__init__(id, description)
     92          if self.id == self.dmdRootName:
     93              self.createCatalog()
     94              self.buildZProperties()
     95
     96
     97 -    def find(self, query):
     98          """Find a service class by is serviceKey.
     99          """
    100          cat = getattr(self, self.default_catalog, None)
    101          if not cat: return
    102          brains = cat({'serviceKeys': query})
    103          if not brains: return None
    104          for brain in brains:
    105              if brain.getPrimaryId.startswith(self.getPrimaryId()):
    106                  try:
    107                      return self.getObjByPath(brain.getPrimaryId)
    108                  except KeyError:
    109                      log.warn("bad path '%s' for index '%s'",
    110                          brain.getPrimaryId, self.default_catalog)
    111
    112
    113 -    def checkValidId(self, id):
    114          """Checks a valid id
    115          """
    116          relationship = getattr(self, 'serviceclasses')
    117          try:
    118              relationship.checkValidId(id)
    119              return True
    120          except Exception as e:
    121              return str(e)
    122
    123
    124 -    def getSubClassesGen(self):
    125          """Return generator that goes through all process classes.
    126          """
    127          for proc in self.serviceclasses.objectValuesGen():
    128              yield proc
    129          for subgroup in self.children():
    130              for proc in subgroup.getSubClassesGen():
    131                  yield proc
    132
    133
    134 -    def getSubClassesSorted(self):
    135          '''Return list of the process classes sorted by sequence.
    136          '''
    137          procs = sorted(self.getSubClassesGen(),
    138                      key=lambda a: a.sequence)
    139          # reset sequence numbers to 0-n
    140          for i, p in enumerate(procs):
    141              p.sequence = i
    142          return procs
    143
    144
    145 -    def countClasses(self):
    146          """Count all serviceclasses with in a ServiceOrganizer.
    147          """
    148          count = self.serviceclasses.countObjects()
    149          for group in self.children():
    150              count += group.countClasses()
    151          return count
    152
    153
    154 -    def createServiceClass(self, name="", description="",
    155                             path="", factory=ServiceClass, **kwargs):
    156          """Create a service class (or retrun existing) based on keywords.
    157          """
    158          svcs = self.getDmdRoot(self.dmdRootName)
    159          svcorg = svcs.createOrganizer(path)
    160          svccl = svcorg.find(name)
    161          if not svccl:
    162              svccl = factory(name, (name,),description=description, **kwargs)
    163              svcorg.serviceclasses._setObject(svccl.id, svccl)
    164              svccl = svcorg.serviceclasses._getOb(svccl.id)
    165          return svccl
    166
    167 -    def saveZenProperties(self, pfilt=iszprop, REQUEST=None):
    168          """
    169          Save all ZenProperties found in the REQUEST.form object.
    170          Overridden so that service instances can be re-indexed if needed
    171          """
    172          #get value to see if it changes
    173          monitor = self.zMonitor
    174          result = super(ServiceOrganizer, self).saveZenProperties( pfilt, REQUEST)
    175
    176          if monitor != self.zMonitor :
    177              #indexes need to be updated so that the updated config will be sent
    178              #can be slow if done at /Services would be nice to run asynch
    179              self._indexServiceClassInstances()
    180          return result
    181
    182 -    def deleteZenProperty(self, propname=None, REQUEST=None):
    183          """
    184          Delete device tree properties from the this DeviceClass object.
    185          Overridden to intercept zMonitor changes
    186          """
    187          monitor = self.zMonitor
    188          result = super(ServiceOrganizer, self).deleteZenProperty( propname, REQUEST)
    189          if monitor != self.zMonitor :
    190              #indexes need to be updated so that the updated config will be sent
    191              #can be slow if done at /Services would be nice to run asynch
    192              self._indexServiceClassInstances()
    193
    194          return result
    195
    196 -    def _indexServiceClassInstances(self):
    197          """
    198          indexes any service class instances in the hierarchy
    199          """
    200          organizers = [self]
    201          while organizers:
    202              for org in organizers:
    203                  for sc in org.serviceclasses():
    204                      sc._indexInstances()
    205
    206              oldOrgs = organizers
    207              organizers = []
    208              for org in oldOrgs:
    209                  organizers.extend(org.children())
    210
    211
    212      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addServiceClass')
    213 -    def manage_addServiceClass(self, id=None, REQUEST=None):
    214          """Create a new service class in this Organizer.
    215          """
    216          if id:
    217              sc = ServiceClass(id)
    218              self.serviceclasses._setObject(id, sc)
    219          if REQUEST or not id:
    220              return self.callZenScreen(REQUEST)
    221          else:
    222              return self.serviceclasses._getOb(id)
    223
    224
    225      security.declareProtected(ZEN_MANAGE_DMD, 'manage_addIpServiceClass')
    226 -    def manage_addIpServiceClass(self, id=None, REQUEST=None):
    227          """Create a new service class in this Organizer.
    228          """
    229          if id:
    230              sc = IpServiceClass(id)
    231              self.serviceclasses._setObject(id, sc)
    232          if REQUEST or not id:
    233              return self.callZenScreen(REQUEST)
    234          else:
    235              return self.serviceclasses._getOb(id)
    236
    237
    238 -    def unmonitorServiceClasses(self, ids=None, REQUEST=None):
    239          return self.monitorServiceClasses(ids, False, REQUEST)
    240
    241
    242 -    def monitorServiceClasses(self, ids=None, monitor=True, REQUEST=None):
    243          """Remove ServiceClasses from an EventClass.
    244          """
    245          if not ids: return self()
    246          if isinstance(ids, basestring): ids = (ids,)
    247          for id in ids:
    248              svc = self.serviceclasses._getOb(id)
    249              svc.setZenProperty("zMonitor", monitor)
    250          if REQUEST: return self()
    251
    252
    253 -    def removeServiceClasses(self, ids=None, REQUEST=None):
    254          """Remove ServiceClasses from an EventClass.
    255          """
    256          if not ids: return self()
    257          if isinstance(ids, basestring): ids = (ids,)
    258          for id in ids:
    259              self.serviceclasses._delObject(id)
    260          if REQUEST: return self()
    261
    262
    263 -    def moveServiceClasses(self, moveTarget, ids=None, REQUEST=None):
    264          """Move ServiceClasses from this EventClass to moveTarget.
    265          """
    266          if not moveTarget or not ids: return self()
    267          if isinstance(ids, basestring): ids = (ids,)
    268          target = self.getChildMoveTarget(moveTarget)
    269          for id in ids:
    270              rec = self.serviceclasses._getOb(id)
    271              rec._operation = 1 # moving object state
    272              self.serviceclasses._delObject(id)
    273              target.serviceclasses._setObject(id, rec)
    274          if REQUEST:
    275              REQUEST['RESPONSE'].redirect(target.getPrimaryUrlPath())
    276
    277
    278 -    def buildZProperties(self):
    279          if hasattr(aq_base(self), "zMonitor"): return
    280          self._setProperty("zMonitor", False, type="boolean")
    281          self._setProperty("zFailSeverity", 5, type="int")
    282          self._setProperty("zHideFieldsFromList", [], type="lines")
    283
    284
    285 -    def reIndex(self):
    286          """Go through all devices in this tree and reindex them."""
    287          zcat = self._getOb(self.default_catalog)
    288          zcat.manage_catalogClear()
    289          for srv in self.getSubOrganizers():
    290              for inst in srv.serviceclasses():
    291                  inst.index_object()
    292
    293
    294 -    def createCatalog(self):
    295          """Create a catalog for ServiceClass searching"""
    296          from Products.ZCatalog.ZCatalog import manage_addZCatalog
    297          manage_addZCatalog(self, self.default_catalog,
    298                              self.default_catalog)
    299          zcat = self._getOb(self.default_catalog)
    300          zcat.addIndex('serviceKeys', 'KeywordIndex')
    301          zcat.addColumn('getPrimaryId')
    302
    303
    304 -    def getUserCommandTargets(self):
    305          ''' Called by Commandable.doCommand() to ascertain objects on which
    306          a UserCommand should be executed.
    307          '''
    308          targets = []
    309          for sc in self.serviceclasses():
    310              targets += sc.getUserCommandTargets()
    311          for so in self.children():
    312              targets += so.getUserCommandTargets()
    313          return targets
    314
    315
    316 -    def getUrlForUserCommands(self):
    317          return self.getPrimaryUrlPath() + '/serviceOrganizerManage'
    318
    319
    320 -    def parseServiceLiveSearchString(self, iddescstr):
    321          """ Parse a string of id and description from a live search
    322          """
    323          id = iddescstr.split(None, 1)[0]
    324          return id
    325
    326
    327  InitializeClass(ServiceOrganizer)
    328