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

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

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