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

# Source Code for Module Products.ZenEvents.EventManagerBase

      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__ = """EventManagerBase
     12  Data connector to backend of the event management system.
     13  """
     14
     15  import time
     16  import random
     17  random.seed()
     18  import logging
     19  log = logging.getLogger("zen.Events")
     20
     21  from AccessControl import ClassSecurityInfo
     22
     23  from Products.ZenModel.ZenModelRM import ZenModelRM
     24  from Products.ZenModel.ZenossSecurity import *
     25  from Products.ZenRelations.RelSchema import *
     26  from Products.ZenUtils import Time
     27  from Products.ZenUtils.guid.interfaces import IGlobalIdentifier
     28
     29  from Products.ZenUtils.Utils import unused
     30  from .HeartbeatUtils import getHeartbeatObjects
     31
     32  __pychecker__="maxargs=16"
     33
     34 -class EventManagerBase(ZenModelRM):
     35      """
     36      Data connector to backend of the event management system.
     37      """
     38
     39      eventStateConversions = (
     40                  ('New',         0),
     41                  ('Acknowledged',1),
     42                  ('Suppressed',  2),
     43                  )
     44
     45      eventActions = ('status', 'history', 'drop')
     46
     47      severityConversions = (
     48          ('Critical', 5),
     49          ('Error', 4),
     50          ('Warning', 3),
     51          ('Info', 2),
     52          ('Debug', 1),
     53          ('Clear', 0),
     54      )
     55      severities = dict([(b, a) for a, b in severityConversions])
     56
     57      priorityConversions = (
     58          ('None', -1),
     59          ('Emergency', 0),
     60          ('Alert', 1),
     61          ('Critical', 2),
     62          ('Error', 3),
     63          ('Warning', 4),
     64          ('Notice', 6),
     65          ('Info', 8),
     66          ('Debug', 10),
     67      )
     68      priorities = dict([(b, a) for a, b in priorityConversions])
     69
     70      statusTable = "status"
     71      detailTable = "detail"
     72      logTable = "log"
     73      lastTimeField = "lastTime"
     74      firstTimeField = "firstTime"
     75      deviceField = "device"
     76      componentField = "component"
     77      eventClassField = "eventClass"
     78      severityField = "severity"
     79      stateField = "eventState"
     80      countField = "count"
     81      prodStateField = "prodState"
     82      DeviceGroupField = "DeviceGroups"
     83      SystemField = "Systems"
     84
     85      DeviceWhere = "\"device = '%s'\" % me.getDmdKey()"
     86      DeviceResultFields = ("eventState", "severity", "component", "eventClass",
     87                            "summary", "firstTime", "lastTime", "count" )
     88      ComponentWhere = ("\"(device = '%s' and component = '%s')\""
     89                        " % (me.device().getDmdKey(), escape_string(me.name()))")
     90      ComponentResultFields = ("eventState", "severity", "eventClass", "summary",
     91                               "firstTime", "lastTime", "count" )
     92      IpAddressWhere = "\"ipAddress='%s'\" % (me.getId())"
     93      EventClassWhere = "\"eventClass like '%s%%'\" % me.getDmdKey()"
     94      EventClassInstWhere = """\"eventClass = '%s' and eventClassKey = '%s'\" % (\
     95                                  me.getEventClass(), me.eventClassKey)"""
     96      DeviceClassWhere = "\"(DeviceClass = '%s' or DeviceClass like '%s/%%') \" % \
     97                           ( me.getDmdKey(), me.getDmdKey() )"
     98
     99      LocationWhere = "\"Location like '%s%%'\" % me.getDmdKey()"
    100      SystemWhere = "\"Systems like '%%|%s%%'\" % me.getDmdKey()"
    101      DeviceGroupWhere = "\"DeviceGroups like '%%|%s%%'\" % me.getDmdKey()"
    102
    103      defaultResultFields = ("eventState", "severity", "device", "component",
    104                             "eventClass", "summary", "firstTime", "lastTime",
    105                             "count" )
    106
    107      defaultFields = ('eventState', 'severity', 'evid')
    108
    109      defaultEventId = ('device', 'component', 'eventClass',
    110                           'eventKey', 'severity')
    111
    112      requiredEventFields = ('device', 'summary', 'severity')
    113
    114      defaultAvailabilityDays = 7
    115      defaultPriority = 3
    116      eventAgingHours = 4
    117      eventAgingSeverity = 4
    118      historyMaxAgeDays = 0
    119
    120      _properties = (
    121          {'id':'backend', 'type':'string','mode':'r', },
    122          {'id':'username', 'type':'string', 'mode':'w'},
    123          {'id':'password', 'type':'string', 'mode':'w'},
    124          {'id':'host', 'type':'string', 'mode':'w'},
    125          {'id':'database', 'type':'string', 'mode':'w'},
    126          {'id':'port', 'type':'int', 'mode':'w'},
    127          {'id':'defaultWhere', 'type':'text', 'mode':'w'},
    128          {'id':'defaultOrderby', 'type':'text', 'mode':'w'},
    129          {'id':'defaultResultFields', 'type':'lines', 'mode':'w'},
    130          {'id':'statusTable', 'type':'string', 'mode':'w'},
    131          {'id':'detailTable', 'type':'string', 'mode':'w'},
    132          {'id':'logTable', 'type':'string', 'mode':'w'},
    133          {'id':'lastTimeField', 'type':'string', 'mode':'w'},
    134          {'id':'firstTimeField', 'type':'string', 'mode':'w'},
    135          {'id':'deviceField', 'type':'string', 'mode':'w'},
    136          {'id':'componentField', 'type':'string', 'mode':'w'},
    137          {'id':'severityField', 'type':'string', 'mode':'w'},
    138          {'id':'countField', 'type':'string', 'mode':'w'},
    139          {'id':'DeviceGroupField', 'type':'string', 'mode':'w'},
    140          {'id':'SystemField', 'type':'string', 'mode':'w'},
    141          {'id':'DeviceWhere', 'type':'string', 'mode':'w'},
    142          {'id':'DeviceResultFields', 'type':'lines', 'mode':'w'},
    143          {'id':'ComponentResultFields', 'type':'lines', 'mode':'w'},
    144          {'id':'EventClassWhere', 'type':'string', 'mode':'w'},
    145          {'id':'EventClassInstWhere', 'type':'string', 'mode':'w'},
    146          {'id':'DeviceClassWhere', 'type':'string', 'mode':'w'},
    147          {'id':'LocationWhere', 'type':'string', 'mode':'w'},
    148          {'id':'SystemWhere', 'type':'string', 'mode':'w'},
    149          {'id':'DeviceGroupWhere', 'type':'string', 'mode':'w'},
    150          {'id':'requiredEventFields', 'type':'lines', 'mode':'w'},
    151          {'id':'defaultEventId', 'type':'lines', 'mode':'w'},
    152          {'id':'defaultFields', 'type':'lines', 'mode':'w'},
    153          {'id':'timeout', 'type':'int', 'mode':'w'},
    154          {'id':'clearthresh', 'type':'int', 'mode':'w'},
    155          {'id':'defaultAvailabilityDays', 'type':'int', 'mode':'w'},
    156          {'id':'defaultPriority', 'type':'int', 'mode':'w'},
    157          {'id':'eventAgingHours', 'type':'int', 'mode':'w'},
    158          {'id':'eventAgingSeverity', 'type':'int', 'mode':'w'},
    159          {'id':'historyMaxAgeDays', 'type':'int', 'mode':'w'},
    160          )
    161
    162      _relations =  (
    163          ("commands", ToManyCont(ToOne, "Products.ZenEvents.EventCommand", "eventManager")),
    164      )
    165
    166      security = ClassSecurityInfo()
    167
    168
    169 -    def __init__(self, id, title='', hostname='localhost', username='root',
    170                   password='', database='events', port=3306,
    171                   defaultWhere='',defaultOrderby='',defaultResultFields=[]):
    172          """
    173          Sets up event database access and initializes the cache.
    174
    175          @param id: A unique id
    176          @type id: string
    177          @param title: A title
    178          @type title: string
    179          @param hostname: The hostname of the events database server
    180          @type hostname: string
    181          @param username: The name of a user with permissions to access the
    182              events database
    183          @type username: string
    184          @param password: The password of the user
    185          @type password: string
    186          @param database: The name of the events database
    187          @type database: string
    188          @param port: The port on which the database server is listening
    189          @type port: int
    190          @param defaultWhere: The default where clause to use when building
    191              queries
    192          @type defaultWhere: string
    193          @param defaultOrderby: The default order by clause to use when building
    194              queries
    195          @type defaultOrderby: string
    196          @param defaultResultFields: DEPRECATED. Currently unused.
    197          @type defaultResultFields: list
    198
    199          """
    200          unused(defaultOrderby, defaultResultFields)
    201          self.id = id
    202          self.title = title
    203          self.username=username
    204          self.password=password
    205          self.database=database
    206          self.host=hostname
    207          self.port=port
    208
    209          self.defaultWhere = defaultWhere
    210          self.defaultOrderby="%s desc, %s desc" % (
    211                              self.severityField, self.lastTimeField)
    212
    213 -    def restrictedUserFilter(self, where):
    214          """This is a hook do not delete me!"""
    215          return where
    216
    217 -    def defaultAvailabilityStart(self):
    218          return Time.USDate(time.time() - 60*60*24*self.defaultAvailabilityDays)
    219
    220
    221 -    def defaultAvailabilityEnd(self):
    222          return Time.USDate(time.time())
    223
    224
    225 -    def getAvailability(self, state, **kw):
    226          import Availability
    227          allowedFilters = (
    228              "device", "component", "eventClass", "systems", "severity",
    229              "prodState", "manager", "agent", "DeviceClass", "Location",
    230              "System", "DeviceGroup", "DevicePriority", "monitor")
    231
    232          for name in allowedFilters:
    233              if hasattr(state, name):
    234                  kw.setdefault(name, getattr(state, name))
    235          if getattr(state, 'startDate', None) is not None:
    236              kw.setdefault('startDate', Time.ParseUSDate(state.startDate))
    237          if getattr(state, 'endDate', None) is not None:
    238              # End date needs to be inclusive of events that occurred on that
    239              # date. So we advance to the last second of the day.
    240              kw.setdefault('endDate', Time.getEndOfDay(Time.ParseUSDate(
    241                  state.endDate)))
    242          kw.setdefault('startDate',
    243                        time.time() - 60*60*24*self.defaultAvailabilityDays)
    244          return Availability.query(self.dmd, **kw)
    245
    246 -    def getHeartbeatObjects(self, failures=True, simple=False, limit=0,
    247              db=None):
    248          return getHeartbeatObjects(failures, limit,
    249                  self.getDmdRoot("Devices") if not simple else None)
    250
    251 -    def getMaxSeverity(self, me):
    252          from Products.Zuul.facades import getFacade
    253          """ Returns the severity of the most severe event. """
    254          zep = getFacade('zep')
    255          try:
    256              # Event class rainbows show all events through DEBUG severity
    257              uuid = IGlobalIdentifier(me).getGUID()
    258              return zep.getWorstSeverityByUuid(uuid)
    259          except TypeError, e:
    260              log.warn("Attempted to query events for %r which does not have a uuid" % self)
    261              return 0
    262
    263
    264      #==========================================================================
    265      # Event sending functions
    266      #==========================================================================
    267
    268      security.declareProtected(ZEN_SEND_EVENTS, 'sendEvents')
    269 -    def sendEvents(self, events):
    270          """Send a group of events to the backend.
    271          """
    272          raise NotImplementedError
    273
    274
    275      security.declareProtected(ZEN_SEND_EVENTS, 'sendEvent')
    276 -    def sendEvent(self, event):
    277          """
    278          Send an event to the backend.
    279
    280          @param event: event
    281          @type event: event object
    282          @todo: implement
    283          """
    284          raise NotImplementedError
    285
    286
    287      #==========================================================================
    288      # Schema management functions
    289      #==========================================================================
    290
    291 -    def getEventStates(self):
    292          """Return a list of possible event states.
    293          """
    294          return self.eventStateConversions
    295
    296 -    def getEventActions(self):
    297          """Return a list of possible event actions.
    298          """
    299          return self.eventActions
    300
    301      security.declareProtected(ZEN_COMMON,'getSeverities')
    302 -    def getSeverities(self):
    303          """Return a list of tuples of severities [('Warning', 3), ...]
    304          """
    305          return self.severityConversions
    306
    307 -    def getSeverityString(self, severity):
    308          """Return a string representation of the severity.
    309          """
    310          try:
    311              return self.severities[severity]
    312          except KeyError:
    313              return "Unknown"
    314
    315 -    def getPriorities(self):
    316          """Return a list of tuples of priorities [('Warning', 3), ...]
    317          """
    318          return self.priorityConversions
    319
    320 -    def getPriorityString(self, priority):
    321          """Return the priority name
    322          """
    323          try:
    324              return self.priorities[priority]
    325          except IndexError:
    326              return "Unknown"
    327
    328 -    def getStatusCssClass(self, status):
    329          if status < 0: status = "unknown"
    330          elif status > 3: status = 3
    331          return "zenstatus_%s" % status
    332
    333 -    def getStatusImgSrc(self, status):
    334          ''' Return the img source for a status number
    335          '''
    336          if status < 0:
    337              src = 'grey'
    338          elif status == 0:
    339              src = 'green'
    340          else:
    341              src = 'red'
    342          return '/zport/dmd/img/%s_dot.png' % src
    343
    344
    345 -    def getEventCssClass(self, severity, acked=False):
    346          """return the css class name to be used for this event.
    347          """
    348          __pychecker__='no-constCond'
    349          value = severity < 0 and "unknown" or severity
    350          acked = acked and "acked" or "noack"
    351          return "zenevents_%s_%s %s" % (value, acked, acked)
    352
    353      #==========================================================================
    354      # Utility functions
    355      #==========================================================================
    356
    357 -    def installIntoPortal(self):
    358          """Install skins into portal.
    359          """
    360          from Products.CMFCore.utils import getToolByName
    361          from Products.CMFCore.DirectoryView import addDirectoryViews
    362          from cStringIO import StringIO
    363          import string
    364
    365          out = StringIO()
    366          skinstool = getToolByName(self, 'portal_skins')
    367          if 'zenevents' not in skinstool.objectIds():
    368              addDirectoryViews(skinstool, 'skins', globals())
    369              out.write("Added 'zenevents' directory view to portal_skins\n")
    370          skins = skinstool.getSkinSelections()
    371          for skin in skins:
    372              path = skinstool.getSkinPath(skin)
    373              path = map(string.strip, string.split(path,','))
    374              if 'zenevents' not in path:
    375                  try: path.insert(path.index('zenmodel'), 'zenevents')
    376                  except ValueError:
    377                      path.append('zenevents')
    378                  path = string.join(path, ', ')
    379                  skinstool.addSkinSelection(skin, path)
    380                  out.write("Added 'zenevents' to %s skin\n" % skin)
    381              else:
    382                  out.write(
    383                      "Skipping %s skin, 'zenevents' is already set up\n" % skin)
    384          return out.getvalue()
    385