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