Package Products :: Package ZenModel :: Package browser :: Module DeviceList |
[hide private]
[frames] | no frames]

# Source Code for Module Products.ZenModel.browser.DeviceList

      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  from Products.Five.browser import BrowserView
     15  from Products.ZenModel.DeviceOrganizer import DeviceOrganizer
     16  from Products.ZenUtils.json import json
     17  from Products.ZenUtils.Utils import formreq, unused, ipsort
     18  from Products.AdvancedQuery import MatchRegexp, Or, Eq, In
     19  from Products.ZenUtils.FakeRequest import FakeRequest
     20  from Products.ZenWidgets import messaging
     21  from Products.ZenWidgets.interfaces import IMessageSender
     22
     23 -class AdvancedQueryDeviceList(object):
     24      """
     25      Adapter providing list of devices according to various criteria.
     26      """
     27 -    def __init__(self, context):
     28          self.context = context
     29
     30 -    def __call__(self, *args, **kwargs):
     31          """
     32          Needs to be definition rather than simple reference due to possibility
     33          of monkeypatching the hook.
     34          """
     35          return self._getAdvancedQueryDeviceList(*args, **kwargs)
     36
     37 -    def _getAdvancedQueryDeviceList(self, offset=0, count=50, filter='',
     38                                     orderby='titleOrId', orderdir='asc'):
     39          """
     40          Ask the catalog for devices matching the criteria specified.
     41          """
     42          context = self.context
     43          if not isinstance(context, DeviceOrganizer):
     44              context = self.context.dmd.Devices
     45          catalog = getattr(context, context.default_catalog)
     46          filter = '(?is).*%s.*' % filter
     47          filterquery = Or(
     48              MatchRegexp('id', filter),
     49              MatchRegexp('titleOrId', filter),
     50              MatchRegexp('getDeviceIp', filter),
     51              MatchRegexp('getProdState', filter),
     52              MatchRegexp('getDeviceClassPath', filter)
     53          )
     54          query = Eq('getPhysicalPath', context.absolute_url_path()
     55                      ) & filterquery
     56          objects = catalog.evalAdvancedQuery(query, ((orderby, orderdir),))
     57          objects = list(objects)
     58          totalCount = len(objects)
     59          offset, count = int(offset), int(count)
     60          obs = objects[offset:offset+count]
     61          return totalCount, obs
     62
     63
     64 -class DeviceList(BrowserView):
     65      """
     66      Populates the device list.
     67      """
     68      @formreq
     69 -    def __call__(self, *args, **kwargs):
     70          return self._getJSONDeviceInfo(*args, **kwargs)
     71
     72      @json
     73 -    def _getJSONDeviceInfo(self, offset=0, count=50, filter='',
     74                             orderby='titleOrId', orderdir='asc'):
     75          """
     76          Get devices under self according to criteria and return results as
     77          JSON.
     78
     79          @return: A JSON representation of a tuple containing a list of lists of
     80          device info, and the total number of matching devices
     81          @rtype: "([[a, b, c], [a, b, c]], 17)"
     82          """
     83          devList = AdvancedQueryDeviceList(self.context)
     84          totalCount, devicelist = devList(offset, count, filter, orderby,
     85                                           orderdir)
     86          obs = [x.getObject() for x in devicelist]
     87          if orderby=='getDeviceIp':
     88              obs.sort(lambda a,b:ipsort(a.getDeviceIp(), b.getDeviceIp()))
     89          if orderdir=='desc': obs.reverse()
     90          results = [ob.getDataForJSON(minSeverity=2) + ['odd'] for ob in obs]
     91          return results, totalCount
     92
     93
     94 -class DeviceBatch(BrowserView):
     95      """
     96      Given various criteria, figure out what devices are relevant and execute
     97      the action specified.
     98      """
     99      @formreq
    100 -    def __call__(self, *args, **kwargs):
    101          return self._setDeviceBatchProps(*args, **kwargs)
    102
    103      @property
    104 -    def id(self):
    105          """
    106          This can appear in the acquisition chain, and ZenModelBase.getDmd needs
    107          an id attribute.
    108          """
    109          return self.context.id
    110
    111 -    def _setDeviceBatchProps(self, method='', extraarg=None,
    112                               selectstatus='none', goodevids=[],
    113                               badevids=[], offset=0, count=50, filter='',
    114                               orderby='titleOrId', orderdir='asc', **kwargs):
    115          d = {'lockDevicesFromUpdates':'sendEventWhenBlocked',
    116               'lockDevicesFromDeletion':'sendEventWhenBlocked',
    117               'unlockDevices':'',
    118               'setGroups':'groupPaths',
    119               'setSystems':'systemPaths',
    120               'setLocation':'locationPath',
    121               'setPerformanceMonitor':'performanceMonitor',
    122               'moveDevices':'moveTarget',
    123               'removeDevices':('deleteStatus', 'deleteHistory', 'deletePerf'),
    124               'setProdState':'state',
    125               'setPriority':'priority'
    126              }
    127          if not method or not method in d:
    128              IMessageSender(self.request).sendToBrowser(
    129                  'Unable to Perform Action',
    130                  'An empty or invalid action was attempted.',
    131                  priority=messaging.CRITICAL
    132              )
    133              return self()
    134
    135          request = FakeRequest()
    136          argdict = dict(REQUEST=request)
    137          if d[method]:
    138              if type(d[method]) in [tuple, list]:
    139                  for argName in d[method]:
    140                      argdict[argName] = self.request.get(argName, None)
    141              else:
    142                  argdict[d[method]] = extraarg
    143          action = getattr(self.context, method)
    144          argdict['deviceNames'] = self._getDeviceBatch(selectstatus,
    145                                    goodevids, badevids, offset, count,
    146                                    filter, orderby, orderdir)
    147          # This will call the method on the context, which will redirect to a
    148          # new (or the same) screen and set a message
    149          try:
    150              result = action(**argdict)
    151          except:
    152              msgs = {'lockDevicesFromUpdates':'lock devices from updates',
    153                      'lockDevicesFromDeletion':'lock devices from deletion',
    154                      'unlockDevices':'unlock devices',
    155                      'setGroups':'change device groups',
    156                      'setSystems':'change device systems',
    157                      'setLocation':'set the location',
    158                      'setPerformanceMonitor':'set the performance monitor',
    159                      'moveDevices':'move devices',
    160                      'removeDevices':'delete devices',
    161                      'setProdState':'set production state',
    162                      'setPriority':'set priority'
    163                  }
    164              IMessageSender(self.request).sendToBrowser(
    165                  'Unable to Perform Action',
    166                  'There was an error attempting to %s.' % msgs[method],
    167                  priority=messaging.CRITICAL
    168              )
    169          else:
    170              return result
    171
    172 -    def _getDeviceBatch(self, selectstatus='none', goodevids=[],
    173                         badevids=[], offset=0, count=50, filter='',
    174                         orderby='titleOrId', orderdir='asc'):
    175          unused(count, offset, orderby, orderdir)
    176          if not isinstance(goodevids, (list, tuple)):
    177              goodevids = [goodevids]
    178          if not isinstance(badevids, (list, tuple)):
    179              badevids = [badevids]
    180          if selectstatus=='all':
    181              idquery = ~In('id', badevids)
    182          else:
    183              idquery = In('id', goodevids)
    184          filter = '(?is).*%s.*' % filter
    185          filterquery = Or(
    186              MatchRegexp('id', filter),
    187              MatchRegexp('titleOrId', filter),
    188              MatchRegexp('getDeviceIp', filter),
    189              MatchRegexp('getProdState', filter),
    190              MatchRegexp('getDeviceClassPath', filter)
    191          )
    192          query = Eq('getPhysicalPath', self.context.absolute_url_path()) & idquery
    193          query = query & filterquery
    194          catalog = getattr(self.context, self.context.default_catalog)
    195          objects = catalog.evalAdvancedQuery(query)
    196          return [x['id'] for x in objects]
    197