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

# Source Code for Module Products.ZenModel.DeviceReport

      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 cgi
     15  import types
     16
     17  from Globals import InitializeClass
     18  from AccessControl import ClassSecurityInfo
     19
     20  from Products.ZenUtils.ZenTales import talesEval
     21  from Products.ZenUtils.Utils import convToUnits, zdecode
     22  from Products.ZenWidgets import messaging
     23
     24
     25  #from Report import Report
     26  from ZenModelRM import ZenModelRM
     27
     28 -def manage_addDeviceReport(context, id, title = None, REQUEST = None):
     29      """Add a DeviceReport
     30      """
     31      dc = DeviceReport(id, title)
     32      context._setObject(id, dc)
     33      if REQUEST is not None:
     34          messaging.IMessageSender(context).sendToBrowser(
     35              'Report Created',
     36              'Device report %s was created.' % id
     37          )
     38          return REQUEST['RESPONSE'].redirect(context.absolute_url() + '/manage_main')
     39
     40
     41
     42 -class DeviceReport(ZenModelRM):
     43
     44      meta_type = "DeviceReport"
     45
     46      path = "/"
     47      deviceQuery = ""
     48      sortedHeader = ""
     49      sortedSence = "asc"
     50      groupby = ""
     51      columns = []
     52      colnames = []
     53
     54      _properties = ZenModelRM._properties + (
     55          {'id':'path', 'type':'string', 'mode':'w'},
     56          {'id':'deviceQuery', 'type':'string', 'mode':'w'},
     57          {'id':'sortedHeader', 'type':'string', 'mode':'w'},
     58          {'id':'sortedSence', 'type':'string', 'mode':'w'},
     59          {'id':'groupby', 'type':'string', 'mode':'w'},
     60          {'id':'columns', 'type':'lines', 'mode':'w'},
     61          {'id':'colnames', 'type':'lines', 'mode':'w'},
     62      )
     63
     64
     65      # Screen action bindings (and tab definitions)
     66      factory_type_information = (
     67          {
     68              'immediate_view' : 'viewDeviceReport',
     69              'actions'        :
     70              (
     71                  {'name'          : 'Report',
     72                  'action'        : 'viewDeviceReport',
     73                  'permissions'   : ("View",),
     74                  },
     75                  {'name'          : 'Edit',
     76                  'action'        : 'editDeviceReport',
     77                  'permissions'   : ("Manage DMD",),
     78                  },
     79              )
     80           },
     81          )
     82
     83      security = ClassSecurityInfo()
     84
     85
     86 -    def getDevices(self):
     87          """Return the device list for this report.
     88          """
     89          devs = self.getDmdRoot("Devices")
     90          if self.path != "/": devs = devs.getOrganizer(self.path)
     91          devlist = devs.getSubDevices()
     92          if self.deviceQuery:
     93              try:
     94                  return [ dev for dev in devlist \
     95                              if talesEval("python:"+self.deviceQuery, dev) ]
     96              except Exception, e:
     97                  return e
     98          return devlist
     99
    100
    101 -    def testQueryStyle(self):
    102          """Return red text style if query is bad.
    103          """
    104          try:
    105              self.getDevices()
    106          except:
    107              return "color:#FF0000"
    108
    109
    110 -    def testColNamesStyle(self):
    111          """Return red text style if columns and colnames not the same length.
    112          """
    113          if len(self.columns) != len(self.colnames): return "color:#FF0000"
    114
    115
    116 -    def reportHeader(self):
    117          h = []
    118          tname = self.getPrimaryId()
    119          for i, field in enumerate(self.columns):
    120              try:name = self.colnames[i]
    121              except IndexError: name = field
    122              h.append(self.ZenTableManager.getTableHeader(tname , field, name))
    123          return "\n".join(h)
    124
    125
    126 -    def reportHeaders(self):
    127          h = []
    128          for i, field in enumerate(self.columns):
    129              try:name = self.colnames[i]
    130              except IndexError: name = field
    131              h.append((field, name))
    132          return h
    133
    134
    135 -    def reportBody(self, batch):
    136          """body of this report create from a filtered and sorted batch.
    137          """
    138          body = []
    139          for dev in batch:
    140              # If the query is invalid, dev will be an exception string
    141              if type(dev) in types.StringTypes:
    142                  body.extend([
    143                      '<tr class="tablevalues">',
    144                      '  <td colspan="%d" align="center">' % len(self.columns),
    145                      '    Query error: %s' % dev,
    146                      '  </td>',
    147                      '</tr>',
    148                      ])
    149              else:
    150                  body.append("<tr class='tablevalues'>")
    151                  for field in self.columns:
    152                      body.append("<td>")
    153                      if field == "getId": field += "Link"
    154
    155                      # Allow the ability to parse Python
    156                      attr = getattr(dev, field, 'Unknown column')
    157                      variables_and_funcs = {
    158                         'device':dev, 'dev':dev, 'attr':attr,
    159                         'convToUnits':convToUnits, 'zdecode':zdecode,
    160                      }
    161                      if field.startswith('python:'):
    162                          expression = field.replace('python:', 'attr=')
    163                          try:
    164                              exec(expression, variables_and_funcs)
    165                              attr = variables_and_funcs['attr']
    166                          except Exception, ex:
    167                              attr = str(ex)
    168
    169                      if callable(attr):
    170                          try: value = attr()
    171                          except Exception, ex:
    172                               value = str(ex)
    173                      else: value = attr
    174
    175                      if type(value) in (types.ListType, types.TupleType):
    176                          # Some calls don't return strings
    177                          try: value = ", ".join(value)
    178                          except Exception, ex:
    179                               value = str(ex)
    180                      if (not field.endswith("Link")
    181                          and type(value) in types.StringTypes):
    182                          value = cgi.escape(value)
    183                      elif type(value) not in types.StringTypes:
    184                          value = str(value)
    185                      body.append(value)
    186                      body.append("</td>")
    187                  body.append("</tr>")
    188
    189          return "\n".join(body)
    190
    191
    192  InitializeClass(DeviceReport)
    193