Package ZenModel :: Module DeviceOrganizer
[hide private]
[frames] | no frames]

Source Code for Module ZenModel.DeviceOrganizer

  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   
 14  import types 
 15  import re 
 16   
 17  from AccessControl import ClassSecurityInfo 
 18  from Globals import InitializeClass 
 19  from Acquisition import aq_parent 
 20   
 21  from Organizer import Organizer 
 22  from DeviceManagerBase import DeviceManagerBase 
 23  from Commandable import Commandable 
 24  from ZenMenuable import ZenMenuable 
 25  from MaintenanceWindowable import MaintenanceWindowable 
 26  from AdministrativeRoleable import AdministrativeRoleable 
 27   
 28  from Products.AdvancedQuery import MatchRegexp, Eq, Or, In 
 29   
 30  from Products.ZenRelations.RelSchema import * 
 31  import simplejson 
 32   
 33  from ZenossSecurity import * 
 34   
35 -class DeviceOrganizer(Organizer, DeviceManagerBase, Commandable, ZenMenuable, 36 MaintenanceWindowable, AdministrativeRoleable):
37 """ 38 DeviceOrganizer is the base class for device organizers. 39 It has lots of methods for rolling up device statistics and information. 40 """ 41 42 security = ClassSecurityInfo() 43 44 # Screen action bindings (and tab definitions) 45 factory_type_information = ( 46 { 47 'immediate_view' : 'deviceOrganizerStatus', 48 'actions' : 49 ( 50 { 'id' : 'status' 51 , 'name' : 'Status' 52 , 'action' : 'deviceOrganizerStatus' 53 , 'permissions' : (ZEN_VIEW, ) 54 }, 55 { 'id' : 'events' 56 , 'name' : 'Events' 57 , 'action' : 'viewEvents' 58 , 'permissions' : (ZEN_VIEW, ) 59 }, 60 { 'id' : 'historyEvents' 61 , 'name' : 'History' 62 , 'action' : 'viewHistoryEvents' 63 , 'permissions' : (ZEN_VIEW, ) 64 }, 65 { 'id' : 'manage' 66 , 'name' : 'Administration' 67 , 'action' : 'deviceOrganizerManage' 68 , 'permissions' : (ZEN_MANAGE_DMD,) 69 }, 70 ) 71 }, 72 ) 73 74 _relations = Organizer._relations + ( 75 ("maintenanceWindows", ToManyCont( 76 ToOne, "Products.ZenModel.MaintenanceWindow", "productionState")), 77 ("adminRoles", ToManyCont( 78 ToOne,"Products.ZenModel.AdministrativeRole","managedObject")), 79 ('userCommands', ToManyCont( 80 ToOne, 'Products.ZenModel.UserCommand', 'commandable')), 81 ('zenMenus', ToManyCont( 82 ToOne, 'Products.ZenModel.ZenMenu', 'menuable')), 83 ) 84 85 security.declareProtected(ZEN_COMMON, "getSubDevices")
86 - def getSubDevices(self, devfilter=None, devrel="devices"):
87 """ 88 Get all the devices under an instance of a DeviceOrganizer 89 90 @param devfilter: Filter function applied to returned list 91 @type devfilter: function 92 @param devrel: Relationship that contains devices 93 @type devrel: string 94 @return: Devices 95 @rtype: list 96 97 98 """ 99 devrelobj = getattr(self, devrel, None) 100 if not devrelobj: 101 raise AttributeError, "%s not found on %s" % (devrel, self.id) 102 devices = filter(devfilter, devrelobj()) 103 devices = [ dev for dev in devices if self.checkRemotePerm(ZEN_VIEW, dev)] 104 for subgroup in self.children(): 105 devices.extend(subgroup.getSubDevices(devfilter, devrel)) 106 return devices
107 108 109 security.declareProtected(ZEN_VIEW, "getSubDevicesGen")
110 - def getSubDevicesGen(self, devrel="devices"):
111 """get all the devices under and instance of a DeviceGroup""" 112 devrelobj = getattr(self, devrel, None) 113 if not devrelobj: 114 raise AttributeError, "%s not found on %s" % (devrel, self.id) 115 for dev in devrelobj.objectValuesGen(): 116 yield dev 117 for subgroup in self.children(): 118 for dev in subgroup.getSubDevicesGen(devrel): 119 yield dev
120
121 - def getSubDevicesGenTest(self, devrel="devices"):
122 """get all the devices under and instance of a DeviceGroup""" 123 devices = getattr(self, devrel, None) 124 if not devices: 125 raise AttributeError, "%s not found on %s" % (devrel, self.id)
126 127
128 - def getMonitoredComponents(self):
129 """Return monitored components for devices within this DeviceOrganizer. 130 """ 131 cmps = [] 132 for dev in self.getSubDevicesGen(): 133 cmps.extend(dev.getMonitoredComponents()) 134 return cmps
135 136
137 - def getAllCounts(self, devrel="devices"):
138 """Count all devices within a device group and get the 139 ping and snmp counts as well""" 140 devices = getattr(self, devrel) 141 pingStatus = 0 142 snmpStatus = 0 143 devCount = devices.countObjects() 144 for dev in devices(): 145 if dev.getPingStatusNumber() > 0: 146 pingStatus += 1 147 if dev.getSnmpStatusNumber() > 0: 148 snmpStatus += 1 149 counts = [devCount, pingStatus, snmpStatus] 150 for group in self.children(): 151 sc = group.getAllCounts() 152 for i in range(3): counts[i] += sc[i] 153 return counts
154 155
156 - def countDevices(self, devrel="devices"):
157 """count all devices with in a device group""" 158 count = self.devices.countObjects() 159 for group in self.children(): 160 count += group.countDevices() 161 return count
162 163
164 - def pingStatus(self, devrel="devices"):
165 """aggrigate ping status for all devices in this group and below""" 166 status = self._status("Ping", devrel) 167 for group in self.children(): 168 status += group.pingStatus() 169 return status
170 171
172 - def snmpStatus(self, devrel="devices"):
173 """aggrigate snmp status for all devices in this group and below""" 174 status = self._status("Snmp", devrel) 175 for group in self.children(): 176 status += group.snmpStatus() 177 return status
178 179
180 - def _buildDeviceList(self, deviceNames):
181 """Build a device list for set methods""" 182 if isinstance(deviceNames, basestring): 183 deviceNames = [deviceNames] 184 return [d for d in self.getSubDevices() 185 if deviceNames is None or d.id in deviceNames 186 or d.getPrimaryId() in deviceNames]
187 188
189 - def deviceClassMoveTargets(self):
190 """Return list of all organizers excluding our self.""" 191 targets = filter(lambda x: x != self.getOrganizerName(), 192 self.dmd.Devices.getOrganizerNames()) 193 targets.sort(lambda x,y: cmp(x.lower(), y.lower())) 194 return targets
195 196
197 - def moveDevicesToClass(self, moveTarget, deviceNames=None, REQUEST=None):
198 """Move Devices from one DeviceClass to Another""" 199 if deviceNames is None: 200 if REQUEST: REQUEST['message'] = "No Devices Selected" 201 return self.callZenScreen(REQUEST) 202 deviceNames = [ x.split('/')[-1] for x in deviceNames ] 203 return self.dmd.Devices.moveDevices(moveTarget, deviceNames, REQUEST)
204 205
206 - def setProdState(self, state, deviceNames=None, 207 isOrganizer=False, REQUEST=None):
208 """Set production state of all devices in this Organizer. 209 """ 210 if deviceNames is None and not isOrganizer: 211 if REQUEST: REQUEST['message'] = "No Devices Selected" 212 return self.callZenScreen(REQUEST) 213 for dev in self._buildDeviceList(deviceNames): 214 dev.setProdState(state) 215 if REQUEST: 216 statename = self.convertProdState(state) 217 REQUEST['message'] = "Production State set to %s" % statename 218 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 219 return REQUEST['message'] 220 else: 221 return self.callZenScreen(REQUEST)
222
223 - def setPriority(self, priority, deviceNames=None, 224 isOrganizer=False, REQUEST=None):
225 """Set prioirty of all devices in this Organizer. 226 """ 227 if deviceNames is None and not isOrganizer: 228 if REQUEST: REQUEST['message'] = "No Devices Selected" 229 return self.callZenScreen(REQUEST) 230 for dev in self._buildDeviceList(deviceNames): 231 dev.setPriority(priority) 232 if REQUEST: 233 priname = self.convertPriority(priority) 234 REQUEST['message'] = "Priority set to %s" % priname 235 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 236 return REQUEST['message'] 237 else: 238 return self.callZenScreen(REQUEST)
239 240
241 - def setStatusMonitors(self, statusMonitors=None, deviceNames=None, 242 isOrganizer=False, REQUEST=None):
243 """ Provide a method to set status monitors from any organizer """ 244 if not statusMonitors: 245 if REQUEST: REQUEST['message'] = "No Monitor Selected" 246 return self.callZenScreen(REQUEST) 247 if deviceNames is None and not isOrganizer: 248 if REQUEST: REQUEST['message'] = "No Devices Selected" 249 return self.callZenScreen(REQUEST) 250 for dev in self._buildDeviceList(deviceNames): 251 dev.setStatusMonitors(statusMonitors) 252 if REQUEST: 253 if len(statusMonitors) == 1: 254 REQUEST['message'] = "Status monitor set to %s" % statusMonitors 255 elif len(statusMonitors) > 1: 256 REQUEST['message'] = "Status monitor set to %s" % ", ".join(statusMonitors) 257 else: 258 REQUEST['message'] = "Status monitor unset" 259 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 260 return REQUEST['message'] 261 else: 262 return self.callZenScreen(REQUEST)
263
264 - def setPerformanceMonitor(self, performanceMonitor=None, deviceNames=None, 265 isOrganizer=False, REQUEST=None):
266 """ Provide a method to set performance monitor from any organizer """ 267 if not performanceMonitor: 268 if REQUEST: REQUEST['message'] = "No Monitor Selected" 269 return self.callZenScreen(REQUEST) 270 if deviceNames is None and not isOrganizer: 271 if REQUEST: REQUEST['message'] = "No Devices Selected" 272 return self.callZenScreen(REQUEST) 273 for dev in self._buildDeviceList(deviceNames): 274 dev.setPerformanceMonitor(performanceMonitor) 275 if REQUEST: 276 REQUEST['message'] = "Performance monitor set to %s" % ( 277 performanceMonitor) 278 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 279 return REQUEST['message'] 280 else: 281 return self.callZenScreen(REQUEST)
282 283
284 - def setGroups(self, groupPaths=None, deviceNames=None, 285 isOrganizer=False, REQUEST=None):
286 """ Provide a method to set device groups from any organizer """ 287 if deviceNames is None and not isOrganizer: 288 if REQUEST: REQUEST['message'] = "No Devices Selected" 289 return self.callZenScreen(REQUEST) 290 if not groupPaths: groupPaths = [] 291 for dev in self._buildDeviceList(deviceNames): 292 dev.setGroups(groupPaths) 293 if REQUEST: 294 if len(groupPaths) == 1: 295 REQUEST['message'] = "Groups set to %s" % groupPaths 296 elif len(groupPaths) > 1: 297 REQUEST['message'] = "Groups set to %s" % ", ".join(groupPaths) 298 else: 299 REQUEST['message'] = "Groups unset" 300 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 301 return REQUEST['message'] 302 else: 303 return self.callZenScreen(REQUEST)
304 305
306 - def setSystems(self, systemPaths=None, deviceNames=None, 307 isOrganizer=False, REQUEST=None):
308 """ Provide a method to set device systems from any organizer """ 309 if deviceNames is None and not isOrganizer: 310 if REQUEST: REQUEST['message'] = "No Devices Selected" 311 return self.callZenScreen(REQUEST) 312 if not systemPaths: systemPaths = [] 313 for dev in self._buildDeviceList(deviceNames): 314 dev.setSystems(systemPaths) 315 if REQUEST: 316 if len(systemPaths) == 1: 317 REQUEST['message'] = "Systems set to %s" % systemPaths 318 elif len(systemPaths) > 1: 319 REQUEST['message'] = "Systems set to %s" % ", ".join(systemPaths) 320 else: 321 REQUEST['message'] = "Systems unset" 322 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 323 return REQUEST['message'] 324 else: 325 return self.callZenScreen(REQUEST)
326
327 - def setLocation(self, locationPath="", deviceNames=None, 328 isOrganizer=False, REQUEST=None):
329 """ Provide a method to set device location from any organizer """ 330 if deviceNames is None and not isOrganizer: 331 if REQUEST: REQUEST['message'] = "No Devices Selected" 332 return self.callZenScreen(REQUEST) 333 for dev in self._buildDeviceList(deviceNames): 334 dev.setLocation(locationPath) 335 if REQUEST: 336 REQUEST['message'] = "Location set to %s" % locationPath 337 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 338 return REQUEST['message'] 339 else: 340 return self.callZenScreen(REQUEST)
341
342 - def unlockDevices(self, deviceNames=None, isOrganizer=False, REQUEST=None):
343 """Unlock devices""" 344 if deviceNames is None and not isOrganizer: 345 if REQUEST: REQUEST['message'] = "No Devices Selected" 346 return self.callZenScreen(REQUEST) 347 for dev in self._buildDeviceList(deviceNames): 348 dev.unlock() 349 if REQUEST: 350 REQUEST['message'] = "Devices unlocked" 351 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 352 return REQUEST['message'] 353 else: 354 return self.callZenScreen(REQUEST)
355
356 - def lockDevicesFromDeletion(self, deviceNames=None, 357 sendEventWhenBlocked=None, isOrganizer=False, REQUEST=None):
358 """Lock devices from being deleted""" 359 if deviceNames is None and not isOrganizer: 360 if REQUEST: REQUEST['message'] = "No Devices Selected" 361 return self.callZenScreen(REQUEST) 362 for dev in self._buildDeviceList(deviceNames): 363 dev.lockFromDeletion(sendEventWhenBlocked) 364 if REQUEST: 365 REQUEST['message'] = "Devices locked from deletion" 366 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 367 return REQUEST['message'] 368 else: 369 return self.callZenScreen(REQUEST)
370
371 - def lockDevicesFromUpdates(self, deviceNames=None, 372 sendEventWhenBlocked=None, isOrganizer=False, REQUEST=None):
373 """Lock devices from being deleted or updated""" 374 if deviceNames is None and not isOrganizer: 375 if REQUEST: REQUEST['message'] = "No Devices Selected" 376 return self.callZenScreen(REQUEST) 377 for dev in self._buildDeviceList(deviceNames): 378 dev.lockFromUpdates(sendEventWhenBlocked) 379 if REQUEST: 380 REQUEST['message'] = "Devices locked from updates and deletion" 381 if REQUEST.has_key('oneKeyValueSoInstanceIsntEmptyAndEvalToFalse'): 382 return REQUEST['message'] 383 else: 384 return self.callZenScreen(REQUEST)
385 386
387 - def index_object(self):
388 """No action. 389 Index of subdevices will happen in manage_addAdministrativeRole 390 """ 391 pass
392
393 - def unindex_object(self):
394 """No action. 395 Unindex of subdevices will happen in manage_deleteAdministrativeRole 396 """ 397 pass
398
399 - def manage_addAdministrativeRole(self, newId, REQUEST=None):
400 """ 401 Overrides AdministrativeRoleable.manage_addAdministrativeRole 402 Adds an administrator to this DeviceOrganizer 403 404 @param userid: User to make an administrator of this Organizer 405 @type userid: string 406 """ 407 AdministrativeRoleable.manage_addAdministrativeRole(self, newId) 408 for dev in self.getSubDevices(): 409 dev = dev.primaryAq() 410 dev.setAdminLocalRoles() 411 if REQUEST: 412 REQUEST['message'] = "Administrative Role %s added" % newId 413 return self.callZenScreen(REQUEST)
414 415
416 - def manage_editAdministrativeRoles(self, ids=(), role=(), 417 level=(), REQUEST=None):
418 """ 419 Overrides AdministrativeRoleable.manage_editAdministrativeRoles 420 Edit the administrators to this DeviceOrganizer 421 """ 422 AdministrativeRoleable.manage_editAdministrativeRoles( 423 self,ids,role,level) 424 for dev in self.getSubDevices(): 425 dev = dev.primaryAq() 426 dev.setAdminLocalRoles() 427 if REQUEST: 428 REQUEST['message'] = "Administrative Roles Updated" 429 return self.callZenScreen(REQUEST)
430 431
432 - def manage_deleteAdministrativeRole(self, delids=(), REQUEST=None):
433 """ 434 Overrides AdministrativeRoleable.manage_deleteAdministrativeRole 435 Deletes administrators to this DeviceOrganizer 436 437 @param delids: Users to delete from this Organizer 438 @type delids: tuple of strings 439 """ 440 AdministrativeRoleable.manage_deleteAdministrativeRole(self, delids) 441 for dev in self.getSubDevices(): 442 dev = dev.primaryAq() 443 dev.setAdminLocalRoles() 444 if REQUEST: 445 REQUEST['message'] = "Administrative Roles Deleted" 446 return self.callZenScreen(REQUEST)
447 448
449 - def manage_snmpCommunity(self, REQUEST=None):
450 """reset Community on all devices in this Organizer. 451 """ 452 [ d.manage_snmpCommunity() for d in self.getSubDevices() ] 453 if REQUEST: 454 return self.callZenScreen(REQUEST)
455
456 - def setManageIp(self, REQUEST=None):
457 """reset ip on all devices in this Organizer. 458 """ 459 [ d.setManageIp() for d in self.getSubDevices() ] 460 if REQUEST: 461 return self.callZenScreen(REQUEST)
462
463 - def collectDevice(self, REQUEST=None):
464 """model all devices in this Organizer. 465 """ 466 [ d.collectDevice() for d in self.getSubDevices() ] 467 if REQUEST: 468 return self.callZenScreen(REQUEST)
469
470 - def _status(self, type, devrel="devices"):
471 """build status info for device in this device group""" 472 status = 0 473 statatt = "get%sStatusNumber" % type 474 devices = getattr(self, devrel, None) 475 if not devices: 476 raise AttributeError, "%s not found on %s" % (devrel, self.id) 477 for device in devices(): 478 if getattr(device, statatt, -1)() > 0: 479 status += 1 480 return status
481 482
483 - def statusColor(self, status):
484 """colors for status fields for device groups""" 485 retval = '#00ff00' 486 if status == -1: 487 retval = "#d02090" 488 elif status == 1: 489 retval = '#ffff00' 490 elif status == 2: 491 retval = '#ff9900' 492 elif status > 2: 493 retval = '#ff0000' 494 return retval
495 496
497 - def getUserCommandTargets(self):
498 ''' Called by Commandable.doCommand() to ascertain objects on which 499 a UserCommand should be executed. 500 ''' 501 return self.getSubDevices()
502 503
504 - def getUrlForUserCommands(self):
505 return self.getPrimaryUrlPath() + '/deviceOrganizerManage'
506 507
508 - def getAdvancedQueryDeviceList(self, offset=0, count=50, filter='', 509 orderby='id', orderdir='asc'):
510 catalog = getattr(self, self.default_catalog) 511 filter = '(?is).*%s.*' % filter 512 filterquery = Or( 513 MatchRegexp('id', filter), 514 MatchRegexp('getDeviceIp', filter), 515 MatchRegexp('getProdState', filter), 516 MatchRegexp('getDeviceClassPath', filter) 517 ) 518 query = Eq('getPhysicalPath', self.absolute_url_path() 519 ) & filterquery 520 objects = catalog.evalAdvancedQuery(query, ((orderby, orderdir),)) 521 objects = list(objects) 522 totalCount = len(objects) 523 offset, count = int(offset), int(count) 524 return totalCount, objects[offset:offset+count]
525 526
527 - def getJSONDeviceInfo(self, offset=0, count=50, filter='', 528 orderby='id', orderdir='asc'):
529 """yo""" 530 totalCount, devicelist = self.getAdvancedQueryDeviceList( 531 offset, count, filter, orderby, orderdir) 532 results = [x.getObject().getDataForJSON() + ['odd'] 533 for x in devicelist] 534 return simplejson.dumps((results, totalCount))
535 536
537 - def getDeviceBatch(self, selectstatus='none', goodevids=[], 538 badevids=[], offset=0, count=50, filter='', 539 orderby='id', orderdir='asc'):
540 if not isinstance(goodevids, (list, tuple)): 541 goodevids = [goodevids] 542 if not isinstance(badevids, (list, tuple)): 543 badevids = [badevids] 544 if selectstatus=='all': 545 idquery = ~In('id', badevids) 546 else: 547 idquery = In('id', goodevids) 548 filterquery = Or( 549 MatchRegexp('id', filter), 550 MatchRegexp('getDeviceIp', filter), 551 MatchRegexp('getProdState', filter), 552 MatchRegexp('getDeviceClassPath', filter) 553 ) 554 query = Eq('getPhysicalPath', self.absolute_url_path()) & idquery 555 query = query & filterquery 556 catalog = getattr(self, self.default_catalog) 557 objects = catalog.evalAdvancedQuery(query) 558 return [x['id'] for x in objects]
559 572 573 574 security.declareProtected(ZEN_VIEW, 'getIconPath')
575 - def getIconPath(self):
576 """ Override the zProperty icon path and return a folder 577 """ 578 return "/zport/dmd/img/icons/folder.png"
579 580 security.declareProtected(ZEN_VIEW, 'getEventPill')
581 - def getEventPill(self, showGreen=True):
582 """ Gets event pill for worst severity """ 583 pill = self.ZenEventManager.getEventPillME(self, showGreen=showGreen) 584 if type(pill)==type([]) and len(pill)==1: return pill[0] 585 return pill
586 587 security.declareProtected(ZEN_VIEW, 'getPrettyLink') 603
604 - def getSubOrganizersEventSummary(self, REQUEST=None):
605 """ Gets event summaries of immediate child organizers """ 606 objects = self.children() 607 return self.ZenEventManager.getObjectsEventSummaryJSON(objects, REQUEST)
608
609 - def getSubDevicesEventSummary(self, REQUEST=None):
610 """ Gets event summaries of child devices """ 611 devs = self.devices() 612 return self.ZenEventManager.getObjectsEventSummaryJSON(devs, REQUEST)
613
614 - def getEventSummaryJSON(self, REQUEST=None):
615 return self.ZenEventManager.getObjectsEventSummary([self], REQUEST)
616 617 InitializeClass(DeviceOrganizer) 618