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

# Source Code for Module Products.ZenEvents.EventClass

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