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 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  __doc__="""EventClass.py
     14
     15  Event class objects
     16  """
     17
     18  import logging
     19  log = logging.getLogger("zen.Events")
     20
     21  import transaction
     22  from zope.interface import implements
     23  from Globals import InitializeClass
     24  from AccessControl import ClassSecurityInfo
     25  from AccessControl import Permissions
     26  from Products.ZenModel.ManagedEntity import ManagedEntity
     27  from Products.ZenModel.ZenossSecurity import *
     28  from Acquisition import aq_base
     29
     30  from Products.ZenRelations.RelSchema import *
     31  from EventClassInst import EventClassInst, EventClassPropertyMixin
     32  from Products.ZenEvents.ZenEventClasses import Unknown
     33
     34  from Products.ZenModel.Organizer import Organizer
     35  from Products.ZenModel.ZenPackable import ZenPackable
     36  from Products.ZenUtils.guid.interfaces import IGloballyIdentifiable
     37  from Products.ZenUtils.Utils import prepId as globalPrepId
     38
     39  __pychecker__='no-argsused'
     40
     41 -def manage_addEventClass(context, id="Events", REQUEST=None):
     42      """make a event class"""
     43      ed = EventClass(id)
     44      context._setObject(id, ed)
     45      if id == "Events":
     46          ed = context._getOb(id)
     47          ed.createCatalog()
     48          ed.buildZProperties()
     49      if REQUEST is not None:
     50          REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     51
     52 -class EventClass(EventClassPropertyMixin, Organizer, ManagedEntity, ZenPackable):
     53      """
     54      EventClass organizer
     55      """
     56
     57      implements(IGloballyIdentifiable)
     58
     59      isInTree = True
     60
     61      transform = ''
     62
     63      meta_type = "EventClass" #FIXME - this is wrong just temp perserving data
     64      event_key = "EventClass"
     65
     66      dmdRootName = "Events"
     67
     68      default_catalog = "eventClassSearch"
     69
     70      _relations = ZenPackable._relations + (
     71          ("instances", ToManyCont(ToOne,"Products.ZenEvents.EventClassInst","eventClass")),
     72          )
     73
     74
     75      _properties = Organizer._properties + \
     76                    EventClassPropertyMixin._properties + \
     77                    ({'id':'transform', 'type':'text', 'mode':'w'},)
     78
     79
     80      # Screen action bindings (and tab definitions)
     81      factory_type_information = (
     82          {
     83              'id'             : 'EventClass',
     84              'meta_type'      : 'EventClass',
     85              'description'    : """Base class for all event classes""",
     86              'icon'           : 'EventClass.gif',
     87              'product'        : 'ZenEvents',
     88              'factory'        : 'manage_addEventClass',
     89              'immediate_view' : 'eventClassStatus',
     90              'actions'        :
     91              (
     92                  { 'id'            : 'classes'
     93                  , 'name'          : 'Classes'
     94                  , 'action'        : 'eventClassStatus'
     95                  , 'permissions'   : (
     96                    Permissions.view, )
     97                  },
     98                  { 'id'            : 'eventList'
     99                  , 'name'          : 'Mappings'
    100                  , 'action'        : 'eventMappingList'
    101                  , 'permissions'   : (
    102                    Permissions.view, )
    103                  },
    104                  { 'id'            : 'events'
    105                  , 'name'          : 'Events'
    106                  , 'action'        : 'viewEvents'
    107                  , 'permissions'   : (
    108                    Permissions.view, )
    109                  },
    110                  { 'id'            : 'config'
    111                  , 'name'          : 'Configuration Properties'
    112                  , 'action'        : 'zPropertyEditNew'
    113                  , 'permissions'   : ("Change Device",)
    114                  },
    115              )
    116           },
    117          )
    118
    119      security = ClassSecurityInfo()
    120
    121      severityConversions = (
    122          ('Critical', 5),
    123          ('Error', 4),
    124          ('Warning', 3),
    125          ('Info', 2),
    126          ('Debug', 1),
    127          ('Clear', 0),
    128          ('Original', -1),
    129      )
    130      severities = dict((b, a) for a, b in severityConversions)
    131
    132 -    def getSubEventClasses(self):
    133          """
    134          Return all EventClass objects below this one.
    135
    136          @return: list of event classes
    137          @rtype: list of EventClass
    138          """
    139          evts = self.children()
    140          for subgroup in self.children():
    141              evts.extend(subgroup.getSubEventClasses())
    142          return evts
    143
    144
    145      security.declareProtected(ZEN_COMMON, "getOrganizerNames")
    146 -    def getOrganizerNames(self, addblank=False, checkPerm=False):
    147          """
    148          Returns a list of all organizer names under this organizer. Overridden
    149          here so that restricted users can get a list of event classes.
    150
    151          @param addblank: If True, add a blank item in the list.
    152          @type addblank: boolean
    153          @return: The DMD paths of all Organizers below this instance.
    154          @rtype: list
    155          @permission: ZEN_COMMON
    156          """
    157          return Organizer.getOrganizerNames(
    158              self, addblank=addblank, checkPerm=checkPerm)
    159
    160
    161 -    def find(self, evClassKey):
    162          """
    163          Look for the eventClassKey mapping in an event class,
    164          and return them in sequence number oder, lowest-to-highest.
    165
    166          @parameter evClassKey: event class key
    167          @type evClassKey: string
    168          @return: list of event class mappings that match evClassKey, sorted
    169          @rtype: list of EventClassInst
    170          """
    171          cat = self._getCatalog()
    172          matches = cat({'eventClassKey': evClassKey})
    173          insts = [ self.getObjByPath(b.getPrimaryId) for b in matches ]
    174          insts.sort(lambda x,y: cmp(x.sequence, y.sequence))
    175          if evClassKey != "defaultmapping":
    176              insts.extend(self.find("defaultmapping"))
    177          return insts
    178
    179
    180 -    def lookup(self, evt, device):
    181          """
    182          Given an event, return an event class organizer object
    183
    184          @parameter evt: an event
    185          @type evt: dictionary
    186          @parameter device: device object
    187          @type device: DMD device
    188          @return: an event class that matches the mapping
    189          @rtype: EventClassInst
    190          """
    191          evtcls = []
    192          if getattr(evt, "eventClass", False):
    193              try:
    194                  log.debug("Looking for event class named in event: %s",
    195                            evt.eventClass)
    196                  path = evt.eventClass
    197                  if path.startswith("/"): path = path[1:]
    198                  return self.getDmdRoot('Events').findChild(path)
    199              except (AttributeError, 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 isinstance(ids, basestring): 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 isinstance(ids, basestring): 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      security.declareProtected(ZEN_MANAGE_EVENTS, 'manage_editEventClassTransform')
    321 -    def manage_editEventClassTransform(self, transform = '', REQUEST=None):
    322          "Save the transform"
    323          self.transform = transform
    324          if REQUEST: return self.callZenScreen(REQUEST)
    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          for evtclass in self.getSubEventClasses():
    345              for ip in evtclass.instances():
    346                  ip.index_object()
    347
    348
    349 -    def createCatalog(self):
    350          """Create a catalog for EventClassRecord searching"""
    351          from Products.ZCatalog.ZCatalog import manage_addZCatalog
    352          manage_addZCatalog(self, self.default_catalog,
    353                              self.default_catalog)
    354          zcat = self._getOb(self.default_catalog)
    355          zcat.addIndex('eventClassKey', 'FieldIndex')
    356          zcat.addColumn('getPrimaryId')
    357
    358
    359      security.declareProtected(ZEN_ZPROPERTIES_VIEW, 'getOverriddenObjects')
    360 -    def getOverriddenObjects(self, propname, showDevices=False):
    361          """
    362          Get the objects that override a property somewhere below in the tree
    363          This method overrides ZenPropertyManager
    364          """
    365          objects = []
    366          for inst in self.getSubInstances('instances'):
    367              if inst.isLocal(propname) and inst not in objects:
    368                  objects.append(inst)
    369          for suborg in self.children():
    370              if suborg.isLocal(propname):
    371                  objects.append(suborg)
    372              for inst in suborg.getOverriddenObjects(propname):
    373                  if inst not in objects:
    374                      objects.append(inst)
    375          return objects
    376
    377      security.declareProtected(ZEN_VIEW, 'getIconPath')
    378 -    def getIconPath(self):
    379          """ Override the zProperty icon path and return a folder
    380          """
    381          return "/zport/dmd/img/icons/folder.png"
    382
    383      security.declareProtected(ZEN_VIEW, 'getPrettyLink')
    384 -    def getPrettyLink(self, noicon=False, shortDesc=False):
    385          """ Gets a link to this object, plus an icon """
    386          href = self.getPrimaryUrlPath().replace('%','%%')
    387          linktemplate = "<a href='"+href+"' class='prettylink'>%s</a>"
    388          icon = ("<div class='device-icon-container'> "
    389                  "<img class='device-icon' src='%s'/> "
    390                  "</div>") % self.getIconPath()
    391          name = self.getPrimaryDmdId()
    392          if noicon: icon=''
    393          if shortDesc: name = self.id
    394          rendered = icon + name
    395          if not self.checkRemotePerm("View", self):
    396              return rendered
    397          else:
    398              return linktemplate % rendered
    399
    400  InitializeClass(EventClass)
    401