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

# Source Code for Module Products.ZenModel.ServiceOrganizer

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