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

Source Code for Module Products.ZenEvents.EventManagerBase

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