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' : '',
     69              'actions'        :
     70              (
     71                  {'name'          : 'View Report',
     72                  'action'        : '',
     73                  'permissions'   : ("View",),
     74                  },
     75                  {'name'          : 'Edit Report',
     76                  'action'        : 'editDeviceReport',
     77                  'permissions'   : ("Manage DMD",),
     78                  },
     79              )
     80           },
     81          )
     82
     83      security = ClassSecurityInfo()
     84
     85 -    def getBreadCrumbUrlPath(self):
     86          '''
     87          Return the url to be used in breadcrumbs for this object.
     88          '''
     89          return self.getPrimaryUrlPath() + '/editDeviceReport'
     90
     91
     92 -    def getDevices(self):
     93          """Return the device list for this report.
     94          """
     95          devs = self.getDmdRoot("Devices")
     96          if self.path != "/": devs = devs.getOrganizer(self.path)
     97          devlist = devs.getSubDevices()
     98          if self.deviceQuery:
     99              try:
    100                  return [ dev for dev in devlist \
    101                              if talesEval("python:"+self.deviceQuery, dev) ]
    102              except Exception, e:
    103                  return e
    104          return devlist
    105
    106
    107 -    def testQueryStyle(self):
    108          """Return red text style if query is bad.
    109          """
    110          try:
    111              self.getDevices()
    112          except:
    113              return "color:#FF0000"
    114
    115
    116 -    def testColNamesStyle(self):
    117          """Return red text style if columns and colnames not the same length.
    118          """
    119          if len(self.columns) != len(self.colnames): return "color:#FF0000"
    120
    121
    122 -    def reportHeader(self):
    123          h = []
    124          tname = self.getPrimaryId()
    125          for i, field in enumerate(self.columns):
    126              try:name = self.colnames[i]
    127              except IndexError: name = field
    128              h.append(self.ZenTableManager.getTableHeader(tname , field, name))
    129          return "\n".join(h)
    130
    131
    132 -    def reportHeaders(self):
    133          h = []
    134          for i, field in enumerate(self.columns):
    135              try:name = self.colnames[i]
    136              except IndexError: name = field
    137              h.append((field, name))
    138          return h
    139
    140
    141 -    def reportBody(self, batch):
    142          """body of this report create from a filtered and sorted batch.
    143          """
    144          body = []
    145          for dev in batch:
    146              # If the query is invalid, dev will be an exception string
    147              if type(dev) in types.StringTypes:
    148                  body.extend([
    149                      '<tr class="tablevalues">',
    150                      '  <td colspan="%d" align="center">' % len(self.columns),
    151                      '    Query error: %s' % dev,
    152                      '  </td>',
    153                      '</tr>',
    154                      ])
    155              else:
    156                  body.append("<tr class='tablevalues'>")
    157                  for field in self.columns:
    158                      body.append("<td>")
    159                      if field == "getId": field += "Link"
    160
    161                      # Allow the ability to parse Python
    162                      attr = getattr(dev, field, 'Unknown column')
    163                      variables_and_funcs = {
    164                         'device':dev, 'dev':dev, 'attr':attr,
    165                         'convToUnits':convToUnits, 'zdecode':zdecode,
    166                      }
    167                      if field.startswith('python:'):
    168                          expression = field.replace('python:', 'attr=')
    169                          try:
    170                              exec(expression, variables_and_funcs)
    171                              attr = variables_and_funcs['attr']
    172                          except Exception, ex:
    173                              attr = str(ex)
    174
    175                      if callable(attr):
    176                          try: value = attr()
    177                          except Exception, ex:
    178                               value = str(ex)
    179                      else: value = attr
    180
    181                      if type(value) in (types.ListType, types.TupleType):
    182                          # Some calls don't return strings
    183                          try: value = ", ".join(value)
    184                          except Exception, ex:
    185                               value = str(ex)
    186                      if (not field.endswith("Link")
    187                          and type(value) in types.StringTypes):
    188                          value = cgi.escape(value)
    189                      elif type(value) not in types.StringTypes:
    190                          value = str(value)
    191                      body.append(value)
    192                      body.append("</td>")
    193                  body.append("</tr>")
    194
    195          return "\n".join(body)
    196
    197
    198  InitializeClass(DeviceReport)
    199