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