def setPerformanceMonitor(self, performanceMonitor, newPerformanceMonitor=None, REQUEST=None):
    """
    Set the performance monitor for this device.
    If newPerformanceMonitor is passed in create it

    @permission: ZEN_CHANGE_DEVICE
    """
    if newPerformanceMonitor:
        # self.dmd.RenderServer.moveRRDFiles(self.id,
        #    newPerformanceMonitor, performanceMonitor, REQUEST)
        performanceMonitor = newPerformanceMonitor

    obj = self.getDmdRoot("Monitors").getPerformanceMonitor(performanceMonitor)
    try:
        if self.getPerformanceServerName() == performanceMonitor:
            raise
        if self.getPerformanceServer().renderurl == "/zport/RenderServer":
            self.dmd.RenderServer.packageRRDFiles(self.id)
            self.dmd.RenderServer.deleteRRDFiles(self.id)
        else:
            os.system(
                "ssh %s tar -C%s -czf - . > %s/%s.tgz"
                % (
                    self.getPerformanceServer().id,
                    performancePath("/Devices/%s" % self.id),
                    self.dmd.RenderServer.tmpdir,
                    self.id,
                )
            )
            os.system("ssh %s rm -fr %s" % (self.getPerformanceServer().id, performancePath("/Devices/%s" % self.id)))
        if obj.renderurl == "/zport/RenderServer":
            self.dmd.RenderServer.unpackageRRDFiles(self.id)
        else:
            os.system(
                'cat %s/%s.tgz | ssh %s "(mkdir -p %s && tar -C%s -xzf - )"'
                % (
                    self.dmd.RenderServer.tmpdir,
                    self.id,
                    obj.id,
                    performancePath("/Devices/%s" % self.id),
                    performancePath("/Devices/%s" % self.id),
                )
            )
        os.unlink("%s/%s.tgz" % (self.dmd.RenderServer.tmpdir, self.id))
    except:
        pass
    self.addRelation("perfServer", obj)
    self.setLastChange()

    if REQUEST:
        messaging.IMessageSender(self).sendToBrowser(
            "Monitor Changed", "Performance monitor has been set to %s." % performanceMonitor
        )
        return self.callZenScreen(REQUEST)
Beispiel #2
0
    def deleteRRDFiles(self,
                       device,
                       datasource=None,
                       datapoint=None,
                       remoteUrl=None,
                       REQUEST=None):
        """
        Delete RRD files associated with the given device id.
        If datapoint is not None then delete the file corresponding to that dp.
        Else if datasource is not None then delete the files corresponding to
          all datapoints in the datasource.
        Else delete all RRD files associated with the given device.

        @param device: device name
        @param datasource: RRD datasource (DS) name
        @param datapoint: RRD datapoint name (lives in a DS)
        @param remoteUrl: if the RRD is not here, where it lives
        @param REQUEST: URL-marshalled object containg URL options
        """
        # If remoteUrl is specified, open/invoke that first because we
        # probably want to delete RRD files on some other machine.
        if remoteUrl:
            urllib.urlopen(remoteUrl)
        # Carry on with deleting local RRD files; however, if remoteUrl was
        # specified, then the devDir path (probably) doesn't exist on this
        # machine.
        devDir = performancePath('/Devices/%s' % device)
        if not os.path.isdir(devDir):
            return
        fileNames = []
        dirNames = []
        if datapoint:
            fileNames = [
                performancePath('/Devices/%s/%s.rrd' % (device, datapoint))
            ]
        elif datasource:
            rrdPath = '/Devices/%s/%s_*.rrd' % (device, datasource)
            fileNames = glob.glob(performancePath(rrdPath))
        else:
            for dPath, dNames, dFiles in os.walk(devDir, topdown=False):
                fileNames += [os.path.join(dPath, f) for f in dFiles]
                dirNames += [os.path.join(dPath, d) for d in dNames]
            dirNames.append(devDir)
        for fileName in fileNames:
            try:
                os.remove(fileName)
            except OSError:
                log.warn("File %s does not exist" % fileName)
        for dirName in dirNames:
            try:
                os.rmdir(dirName)
            except OSError:
                log.warn('Directory %s could not be removed' % dirName)
    def deleteRRDFiles(self, device,
                        datasource=None, datapoint=None,
                        remoteUrl=None, REQUEST=None):
        """
        Delete RRD files associated with the given device id.
        If datapoint is not None then delete the file corresponding to that dp.
        Else if datasource is not None then delete the files corresponding to
          all datapoints in the datasource.
        Else delete all RRD files associated with the given device.

        @param device: device name
        @param datasource: RRD datasource (DS) name
        @param datapoint: RRD datapoint name (lives in a DS)
        @param remoteUrl: if the RRD is not here, where it lives
        @param REQUEST: URL-marshalled object containg URL options
        """
        # If remoteUrl is specified, open/invoke that first because we
        # probably want to delete RRD files on some other machine.
        if remoteUrl:
            urllib.urlopen(remoteUrl)
        # Carry on with deleting local RRD files; however, if remoteUrl was
        # specified, then the devDir path (probably) doesn't exist on this
        # machine.
        devDir = performancePath('/Devices/%s' % device)
        if not os.path.isdir(devDir):
            return
        fileNames = []
        dirNames = []
        if datapoint:
            fileNames = [
                performancePath('/Devices/%s/%s.rrd' % (device, datapoint))]
        elif datasource:
            rrdPath = '/Devices/%s/%s_*.rrd' % (device, datasource)
            fileNames = glob.glob(performancePath(rrdPath))
        else:
            for dPath, dNames, dFiles in os.walk(devDir, topdown=False):
                fileNames += [os.path.join(dPath, f) for f in dFiles]
                dirNames += [os.path.join(dPath, d) for d in dNames]
            dirNames.append(devDir)
        for fileName in fileNames:
            try:
                os.remove(fileName)
            except OSError:
                log.warn("File %s does not exist" % fileName)
        for dirName in dirNames:
            try:
                os.rmdir(dirName)
            except OSError:
                log.warn('Directory %s could not be removed' % dirName)
def setPerformanceMonitor(self,
                          performanceMonitor,
                          newPerformanceMonitor=None,
                          REQUEST=None):
    """
    Set the performance monitor for this device.
    If newPerformanceMonitor is passed in create it

    @permission: ZEN_CHANGE_DEVICE
    """
    if newPerformanceMonitor:
        #self.dmd.RenderServer.moveRRDFiles(self.id,
        #    newPerformanceMonitor, performanceMonitor, REQUEST)
        performanceMonitor = newPerformanceMonitor

    obj = self.getDmdRoot("Monitors").getPerformanceMonitor(performanceMonitor)
    try:
        if self.getPerformanceServerName() == performanceMonitor: raise
        if self.getPerformanceServer().renderurl == '/zport/RenderServer':
            self.dmd.RenderServer.packageRRDFiles(self.id)
            self.dmd.RenderServer.deleteRRDFiles(self.id)
        else:
            os.system('ssh %s tar -C%s -czf - . > %s/%s.tgz' %
                      (self.getPerformanceServer().id,
                       performancePath('/Devices/%s' % self.id),
                       self.dmd.RenderServer.tmpdir, self.id))
            os.system('ssh %s rm -fr %s' %
                      (self.getPerformanceServer().id,
                       performancePath('/Devices/%s' % self.id)))
        if obj.renderurl == '/zport/RenderServer':
            self.dmd.RenderServer.unpackageRRDFiles(self.id)
        else:
            os.system(
                'cat %s/%s.tgz | ssh %s "(mkdir -p %s && tar -C%s -xzf - )"' %
                (self.dmd.RenderServer.tmpdir, self.id, obj.id,
                 performancePath('/Devices/%s' % self.id),
                 performancePath('/Devices/%s' % self.id)))
        os.unlink('%s/%s.tgz' % (self.dmd.RenderServer.tmpdir, self.id))
    except:
        pass
    self.addRelation("perfServer", obj)
    self.setLastChange()

    if REQUEST:
        messaging.IMessageSender(self).sendToBrowser(
            'Monitor Changed',
            'Performance monitor has been set to %s.' % performanceMonitor)
        return self.callZenScreen(REQUEST)
    def _writeRRD(self, rrdCmd):
       # Stores the value into an RRD file
       # rrd.put() params:
       # @name : RRD Name (String)
       # @value : Data value to be stored (Number)
       # @rrd_type : RRD Data type, Example: GAUGE, COUNTER, DERIVE, ... (String)
       try:
          from Products.ZenModel.PerformanceConf import performancePath
          from Products.ZenRRD.RRDUtil import RRDUtil

          log.info('Writing into RRD File in %s... | Value: %r (%r)' % ( performancePath('totalPower.rrd'), self._preferences.totalPower, type(self._preferences.totalPower)))
          
          # 1st param: RRD Create Command
          # 2nd param: Step
          rrd = RRDUtil(rrdCmd, 300)          
          value2 = rrd.save("totalPower", self._preferences.totalPower, "GAUGE", min=0, max=None)		# This command will write to zenoss/perf/

          log.info("Finished Writing. Return Value: %s" % (value2))
       except Exception, ex:
          summary = "Unable to save data value into RRD file %s . (Exception: \'%s\')" % \
             ("totalPower.rrd", ex)
          log.error(summary)
          
          # Send Error Event to Zenoss
          self._eventService.sendEvent(dict(
             summary = summary,
             message = 'Error Test',
             component = self._preferences.collectorName,
             eventClass = '/Perf/Snmp',
             device = None,
             severity = Error,
             agent = self._preferences.collectorName
             ))
 def buildOptions(self):
     ZCmdBase.buildOptions(self)
     self.parser.add_option('-s',
                            '--step',
                            dest='step',
                            type='int',
                            default=300,
                            help='Default step size in seconds')
     self.parser.add_option('-r',
                            '--root',
                            dest='root',
                            default=performancePath(''),
                            help='Root tree to convert')
     self.parser.add_option('-f',
                            '--file',
                            dest='filename',
                            help='Root tree to convert')
     self.parser.add_option('--commit',
                            dest='commit',
                            action='store_true',
                            default=False,
                            help='Really put the converted files in place.')
     self.parser.add_option('--monitor',
                            dest='monitor',
                            default='localhost',
                            help='Name of this collection host.')
    def performancePath(self, path):
        """
        Given a path, return its location from $ZENHOME and the
        perf/ directories.

        @param path: name for a datapoint in a path (eg device/component/datasource_datapoint)
        @type path: string
        @return: absolute path
        @rtype: string
        """
        from Products.ZenModel.PerformanceConf import performancePath
        return performancePath(path)
Beispiel #8
0
    def unpackageRRDFiles(self, device, REQUEST=None):
        """
        Untar a package of RRDFiles

        @param device: device name
        @param REQUEST: URL-marshalled object containg URL options
        """
        destdir = performancePath('/Devices/%s' % device)
        tarfilename = '%s/%s.tgz' % (self.tmpdir, device)
        log.debug( "Untarring %s into %s" % ( tarfilename, destdir ))
        tar = tarfile.open(tarfilename, "r:gz")
        for file in tar.getmembers():
            tar.extract(file, destdir)
        tar.close()
Beispiel #9
0
    def packageRRDFiles(self, device, REQUEST=None):
        """
        Tar up RRD files into a nice, neat package

        @param device: device name
        @param REQUEST: URL-marshalled object containg URL options
        """
        srcdir = performancePath('/Devices/%s' % device)
        tarfilename = '%s/%s.tgz' % (self.tmpdir, device)
        log.debug( "tarring up %s into %s" % ( srcdir, tarfilename ))
        tar = tarfile.open(tarfilename, "w:gz")
        for file in os.listdir(srcdir):
            tar.add('%s/%s' % (srcdir, file), '/%s' % os.path.basename(file))
        tar.close()
 def buildOptions(self):
     ZCmdBase.buildOptions(self)
     self.parser.add_option('-s', '--step', dest='step', type='int',
                            default=300, help='Default step size in seconds')
     self.parser.add_option('-r', '--root', dest='root', 
                            default=performancePath(''),
                            help='Root tree to convert')
     self.parser.add_option('-f', '--file', dest='filename', 
                            help='Root tree to convert')
     self.parser.add_option('--commit', dest='commit', action='store_true',
                            default=False,
                            help='Really put the converted files in place.')
     self.parser.add_option('--monitor', dest='monitor', 
                            default='localhost',
                            help='Name of this collection host.')
   def buildGraphUrl():

      import zlib
      from urllib import urlencode
      from base64 import urlsafe_b64encode
   
      # Returns a URL for the given graph options and date range.
      from Products.ZenModel.PerformanceConf import performancePath

      graph_def = "-F|-E|--width=800|--height=260|--vertical-label=Watts|--title=Power Consumption|"    # Graph Definitions
      url = "/zport/RenderServer"                                                                      # Render Server URL

      # Build the complete URL, using the RRD file.
      # Graph definition contains the Graph height, width, labels, title, RDD source, Line size, line color, among other things...
      graph_def += "DEF:t1=" + performancePath('totalPower.rrd') + ":ds0:AVERAGE|LINE2:t1#00b200:Power Consumption"

      gopts = graph_def.split('|')      # Graph options, obtained from the graph definition
      drange = 129600                   # Data range

      new_opts = []                     # New graph options for the final URL
      width = 0

      # Assign the width to the new URL
      for o in gopts:
         if o.startswith('--width'):
            width = o.split('=')[1].strip()
            continue
         new_opts.append(o)

      encodedOpts = urlsafe_b64encode(zlib.compress('|'.join(new_opts), 9))
      params = {
         'gopts': encodedOpts,
         'drange': drange,
         'width': width,
      }

      if url.startswith('proxy'):
         url = url.replace('proxy', 'http', 1)
         params['remoteUrl'] = url
         return '/zport/RenderServer/render?%s' % (urlencode(params),)
      else:
         return '%s/render?%s' % (url, urlencode(params),)
 def path(self, dataPoint):
     "The full pathname to RRD file that uses a dataPoint"
     return performancePath(os.path.join(self.rrdPath, dataPoint)) + '.rrd'
Beispiel #13
0
 def path(self, dataPoint):
     "The full pathname to RRD file that uses a dataPoint"
     return performancePath(os.path.join(self.rrdPath, dataPoint)) + '.rrd'