Package Products :: Package ZenEvents :: Module EventClass |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenEvents.EventClass

      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  __doc__="""EventClass.py
     14
     15  Event class objects
     16  """
     17
     18  import types
     19  import logging
     20  log = logging.getLogger("zen.Events")
     21
     22  import transaction
     23  from Globals import InitializeClass
     24  from Globals import DTMLFile
     25  from AccessControl import ClassSecurityInfo
     26  from AccessControl import Permissions
     27  from Products.ZenModel.ManagedEntity import ManagedEntity
     28  from Products.ZenModel.ZenossSecurity import *
     29  from Acquisition import aq_base
     30
     31  from Products.ZenRelations.RelSchema import *
     32  from EventClassInst import EventClassInst, EventClassPropertyMixin
     33  from Products.ZenEvents.ZenEventClasses import Unknown
     34
     35  from Products.ZenModel.Organizer import Organizer
     36  from Products.ZenModel.ZenPackable import ZenPackable
     37
     38  from Products.ZenUtils.Utils import prepId as globalPrepId
     39
     40  __pychecker__='no-argsused'
     41
     42 -def manage_addEventClass(context, id="Events", REQUEST=None):
     43      """make a event class"""
     44      ed = EventClass(id)
     45      context._setObject(id, ed)
     46      if id == "Events":
     47          ed = context._getOb(id)
     48          ed.createCatalog()
     49          ed.buildZProperties()
     50      if REQUEST is not None:
     51          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     52
     53
     54  addEventClass = DTMLFile('dtml/addEventClass',globals())
     55
     56 -class EventClass(EventClassPropertyMixin, Organizer, ManagedEntity, ZenPackable):
     57      """
     58      EventClass organizer
     59      """
     60
     61      isInTree = True
     62
     63      transform = ''
     64
     65      meta_type = "EventClass" #FIXME - this is wrong just temp perserving data
     66      event_key = "EventClass"
     67
     68      dmdRootName = "Events"
     69
     70      default_catalog = "eventClassSearch"
     71
     72      _relations = ZenPackable._relations + (
     73          ("instances", ToManyCont(ToOne,"Products.ZenEvents.EventClassInst","eventClass")),
     74          )
     75
     76
     77      _properties = Organizer._properties + \
     78                    EventClassPropertyMixin._properties + \
     79                    ({'id':'transform', 'type':'text', 'mode':'w'},)
     80
     81
     82      # Screen action bindings (and tab definitions)
     83      factory_type_information = (
     84          {
     85              'id'             : 'EventClass',
     86              'meta_type'      : 'EventClass',
     87              'description'    : """Base class for all event classes""",
     88              'icon'           : 'EventClass.gif',
     89              'product'        : 'ZenEvents',
     90              'factory'        : 'manage_addEventClass',
     91              'immediate_view' : 'eventClassStatus',
     92              'actions'        :
     93              (
     94                  { 'id'            : 'classes'
     95                  , 'name'          : 'Classes'
     96                  , 'action'        : 'eventClassStatus'
     97                  , 'permissions'   : (
     98                    Permissions.view, )
     99                  },
    100                  { 'id'            : 'eventList'
    101                  , 'name'          : 'Mappings'
    102                  , 'action'        : 'eventMappingList'
    103                  , 'permissions'   : (
    104                    Permissions.view, )
    105                  },
    106                  { 'id'            : 'events'
    107                  , 'name'          : 'Events'
    108                  , 'action'        : 'viewEvents'
    109                  , 'permissions'   : (
    110                    Permissions.view, )
    111                  },
    112                  { 'id'            : 'config'
    113                  , 'name'          : 'zProperties'
    114                  , 'action'        : 'zPropertyEdit'
    115                  , 'permissions'   : ("Change Device",)
    116                  },
    117              )
    118           },
    119          )
    120
    121      security = ClassSecurityInfo()
    122
    123      severityConversions = (
    124          ('Critical', 5),
    125          ('Error', 4),
    126          ('Warning', 3),
    127          ('Info', 2),
    128          ('Debug', 1),
    129          ('Clear', 0),
    130          ('Original', -1),
    131      )
    132      severities = dict([(b, a) for a, b in severityConversions])
    133
    134 -    def getSubEventClasses(self):
    135          """
    136          Return all EventClass objects below this one.
    137
    138          @return: list of event classes
    139          @rtype: list of EventClass
    140          """
    141          evts = self.children()
    142          for subgroup in self.children():
    143              evts.extend(subgroup.getSubEventClasses())
    144          return evts
    145
    146
    147      security.declareProtected(ZEN_COMMON, "getOrganizerNames")
    148 -    def getOrganizerNames(self, addblank=False, checkPerm=False):
    149          """
    150          Returns a list of all organizer names under this organizer. Overridden
    151          here so that restricted users can get a list of event classes.
    152
    153          @param addblank: If True, add a blank item in the list.
    154          @type addblank: boolean
    155          @return: The DMD paths of all Organizers below this instance.
    156          @rtype: list
    157          @permission: ZEN_COMMON
    158          """
    159          return Organizer.getOrganizerNames(
    160              self, addblank=addblank, checkPerm=checkPerm)
    161
    162
    163 -    def find(self, evClassKey):
    164          """
    165          Look for the eventClassKey mapping in an event class,
    166          and return them in sequence number oder, lowest-to-highest.
    167
    168          @parameter evClassKey: event class key
    169          @type evClassKey: string
    170          @return: list of event class mappings that match evClassKey, sorted
    171          @rtype: list of EventClassInst
    172          """
    173          cat = self._getCatalog()
    174          matches = cat({'eventClassKey': evClassKey})
    175          insts = [ self.getObjByPath(b.getPrimaryId) for b in matches ]
    176          insts.sort(lambda x,y: cmp(x.sequence, y.sequence))
    177          if evClassKey != "defaultmapping":
    178              insts.extend(self.find("defaultmapping"))
    179          return insts
    180
    181
    182 -    def lookup(self, evt, device):
    183          """
    184          Given an event, return an event class organizer object
    185
    186          @parameter evt: an event
    187          @type evt: dictionary
    188          @parameter device: device object
    189          @type device: DMD device
    190          @return: an event class that matches the mapping
    191          @rtype: EventClassInst
    192          """
    193          evtcls = []
    194          if getattr(evt, "eventClass", False):
    195              try:
    196                  log.debug("Looking for event class named in event: %s",
    197                            evt.eventClass)
    198                  return self.getDmdRoot("Events").getOrganizer(evt.eventClass)
    199              except KeyError:
    200                  log.debug("Unable to find '%s' organizer" % evt.eventClass)
    201
    202          # Use defaultmapping if no eventClassKey is set, or if it blank.
    203          eventClassKey = getattr(evt, 'eventClassKey', 'defaultmapping') \
    204              or 'defaultmapping'
    205
    206          log.debug("No event class specified, searching for eventClassKey %s",
    207                    eventClassKey)
    208          evtcls = self.find(eventClassKey)
    209          log.debug("Found the following event classes that matched key %s: %s",
    210                    eventClassKey, evtcls)
    211
    212          for evtcl in evtcls:
    213              m = evtcl.match(evt, device)
    214              if m:
    215                  log.debug("EventClass %s matched", evtcl.getOrganizerName())
    216                  break
    217          else:
    218              log.debug("No EventClass matched -- using /Unknown")
    219              try:
    220                  return self.getDmdRoot("Events").getOrganizer(Unknown)
    221              except KeyError:
    222                  evtcl = None
    223                  log.debug("Unable to find 'Unknown' organizer")
    224          return evtcl
    225
    226
    227 -    def applyExtraction(self, evt):
    228          """Don't have extraction on event class.
    229          """
    230          return evt
    231
    232
    233 -    def getInstances(self):
    234          """Return all EventClassInstances from this node down.
    235          """
    236          insts = self.instances()
    237          for subclass in self.children():
    238              insts.extend(subclass.getInstances())
    239          return insts
    240
    241
    242 -    def nextSequenceNumber(self, key):
    243          """Get next sequence number for instance.
    244          """
    245          idx = 0
    246          insts = self.find(key)
    247          if len(insts) > 0:
    248              idx = insts[-1].sequence + 1
    249          return idx
    250
    251 -    def prepId(self, id, subchar='_'):
    252          return globalPrepId(id, subchar)
    253
    254 -    def createInstance(self, id=None, REQUEST=None):
    255          """Add an EventClassInst to this EventClass.
    256          """
    257          if id:
    258              id = self.prepId(id)
    259              c=0
    260              while self.instances._getOb(id,False):
    261                  c+=1
    262                  id = "%s_%02d" % (id, c)
    263              ecr = EventClassInst(id)
    264              ecr.sequence = self.nextSequenceNumber(ecr.eventClassKey)
    265              self.instances._setObject(id, ecr)
    266          if REQUEST: return self()
    267          return self.instances._getOb(id)
    268
    269
    270 -    def removeInstances(self, ids=None, REQUEST=None):
    271          """Remove Instances from an EventClass.
    272          """
    273          if not ids: return self()
    274          if type(ids) == types.StringType: ids = (ids,)
    275          for id in ids:
    276              self.instances._delObject(id)
    277          if REQUEST: return self()
    278
    279
    280 -    def moveInstances(self, moveTarget, ids=None, REQUEST=None):
    281          """Move instances from this EventClass to moveTarget.
    282          """
    283          if not moveTarget or not ids: return self()
    284          if type(ids) == types.StringType: ids = (ids,)
    285          target = self.getChildMoveTarget(moveTarget)
    286          for id in ids:
    287              rec = self.instances._getOb(id, None)
    288              if rec is None: continue
    289              rec._operation = 1 # moving object state
    290              self.instances._delObject(id)
    291              target.instances._setObject(id, rec)
    292          if REQUEST:
    293              REQUEST['RESPONSE'].redirect(target.getPrimaryUrlPath())
    294
    295
    296 -    def countInstances(self):
    297          """count all instances with in an event dict"""
    298          count = self.instances.countObjects()
    299          for group in self.children():
    300              count += group.countInstances()
    301          return count
    302
    303
    304 -    def buildZProperties(self):
    305          edict = self.getDmdRoot("Events")
    306          if getattr(aq_base(edict), "zEventAction", False): return
    307          edict._setProperty("zEventClearClasses", [], type="lines")
    308          edict._setProperty("zEventAction", "status")
    309          edict._setProperty("zEventSeverity", -1, type="int")
    310
    311 -    def testTransformStyle(self):
    312          """Test our transform by compiling it.
    313          """
    314          try:
    315              if self.transform:
    316                  compile(self.transform, "<string>", "exec")
    317          except:
    318              return "color:#FF0000;"
    319
    320 -    def manage_editEventClassTransform(self, transform = '', REQUEST=None):
    321          "Save the transform"
    322          self.transform = transform
    323          if REQUEST: return self.callZenScreen(REQUEST)
    324
    325
    326 -    def getEventSeverities(self):
    327          """Return a list of tuples of severities [('Warning', 3), ...]
    328          """
    329          return self.severityConversions
    330
    331 -    def getEventSeverityString(self, severity):
    332          """Return a list of tuples of severities [('Warning', 3), ...]
    333          """
    334          try:
    335              return self.severities[severity]
    336          except IndexError:
    337              return "Unknown"
    338
    339 -    def reIndex(self):
    340          """Go through all ips in this tree and reindex them."""
    341          log.debug("reindexing EventClass:%s", self.getOrganizerName())
    342          zcat = self._getCatalog()
    343          zcat.manage_catalogClear()
    344          transaction.savepoint()
    345          for evtclass in self.getSubEventClasses():
    346              for ip in evtclass.instances():
    347                  ip.index_object()
    348          transaction.savepoint()
    349
    350
    351 -    def createCatalog(self):
    352          """Create a catalog for EventClassRecord searching"""
    353          from Products.ZCatalog.ZCatalog import manage_addZCatalog
    354          manage_addZCatalog(self, self.default_catalog,
    355                              self.default_catalog)
    356          zcat = self._getOb(self.default_catalog)
    357          zcat.addIndex('eventClassKey', 'FieldIndex')
    358          zcat.addColumn('getPrimaryId')
    359
    360
    361      security.declareProtected(ZEN_ZPROPERTIES_VIEW, 'getOverriddenObjects')
    362 -    def getOverriddenObjects(self, propname, showDevices=False):
    363          """
    364          Get the objects that override a property somewhere below in the tree
    365          This method overrides ZenPropertyManager
    366          """
    367          objects = []
    368          for inst in self.getSubInstances('instances'):
    369              if inst.isLocal(propname) and inst not in objects:
    370                  objects.append(inst)
    371          for suborg in self.children():
    372              if suborg.isLocal(propname):
    373                  objects.append(suborg)
    374              for inst in suborg.getOverriddenObjects(propname):
    375                  if inst not in objects:
    376                      objects.append(inst)
    377          return objects
    378
    379      security.declareProtected(ZEN_VIEW, 'getIconPath')
    380 -    def getIconPath(self):
    381          """ Override the zProperty icon path and return a folder
    382          """
    383          return "/zport/dmd/img/icons/folder.png"
    384
    385      security.declareProtected(ZEN_VIEW, 'getPrettyLink')
    386 -    def getPrettyLink(self, noicon=False, shortDesc=False):
    387          """ Gets a link to this object, plus an icon """
    388          href = self.getPrimaryUrlPath().replace('%','%%')
    389          linktemplate = "<a href='"+href+"' class='prettylink'>%s</a>"
    390          icon = ("<div class='device-icon-container'> "
    391                  "<img class='device-icon' src='%s'/> "
    392                  "</div>") % self.getIconPath()
    393          name = self.getPrimaryDmdId()
    394          if noicon: icon=''
    395          if shortDesc: name = self.id
    396          rendered = icon + name
    397          if not self.checkRemotePerm("View", self):
    398              return rendered
    399          else:
    400              return linktemplate % rendered
    401
    402  InitializeClass(EventClass)
    403