Beispiel #1
0
    def testDataSourceAgainstDevice(self, testDevice, REQUEST, write,
                                    errorLog):
        """
        Does the majority of the logic for testing a datasource against the device
        @param string testDevice The id of the device we are testing
        @param Dict REQUEST the browers request
        @param Function write The output method we are using to stream the result of the command
        @parma Function errorLog The output method we are using to report errors
        """
        def writeLines(lines):
            for line in lines.splitlines():
                write(line)

        out = REQUEST.RESPONSE
        # Determine which device to execute against
        device = None
        comp = None
        ttpc = getattr(self.rrdTemplate(), 'targetPythonClass', '')
        ccn = ttpc.rsplit('.', 1)[-1]
        try:
            compClass = getattr(__import__(ttpc, globals(), locals(), [ccn]),
                                ccn)
        except:
            from Products.ZenModel.Device import Device as compClass
        if testDevice:
            # Try to get specified device
            device = self.findDevice(testDevice)
            if not isinstance(device, (compClass, type(None))):
                for comp in device.getMonitoredComponents():
                    if isinstance(comp, compClass): break
                else:
                    comp = None
        elif hasattr(self, 'device'):
            # ds defined on a device, use that device
            device = self.device()
            if not isinstance(device, (compClass, type(None))):
                for comp in device.getMonitoredComponents():
                    if isinstance(comp, compClass): break
                else:
                    comp = None
        elif hasattr(self, 'getSubDevicesGen'):
            # ds defined on a device class, use any device from the class
            for device in self.getSubDevicesGen():
                if isinstance(device, compClass): break
                for comp in device.getMonitoredComponents():
                    if isinstance(comp, compClass): break
                else:
                    comp = None
                if comp: break
            else:
                device = None
        if not comp:
            comp = device
        if not device:
            errorLog('No Testable Device',
                     'Cannot determine a device against which to test.',
                     priority=messaging.WARNING)
            return self.callZenScreen(REQUEST)
        if not comp:
            errorLog('No component found',
                     'Cannot find %s component on device %s.' %
                     (ttpc, device.id),
                     priority=messaging.WARNING)
            return self.callZenScreen(REQUEST)
        from ZenPacks.community.SQLDataSource.SQLClient import SQLClient
        cl = SQLClient(device)

        header = ''
        footer = ''
        # Render
        if REQUEST.get('renderTemplate', True):
            header, footer = self.commandTestOutput().split('OUTPUT_TOKEN')

        out.write(str(header))

        start = time.time()
        try:
            sql, sqlp, kbs, cs = self.getQueryInfo(comp)
            if not sql:
                raise StandardError('query is empty')
            properties = dict([
                (dp.id, dp.getAliasNames() and dp.getAliasNames()[0] or dp.id)
                for dp in self.getRRDDataPoints()
            ])
            write('Executing query: "%s"' % sql)
            write('')
            write('')
            write('Results:')
            rows = cl.query({'t': (sql, {}, cs, properties)})
            if isinstance(rows, Failure):
                raise StandardError(rows.getErrorMessage())
            rows = rows.get('t') or [{}]
            if isinstance(rows, Failure):
                raise StandardError(rows.getErrorMessage())
            write('|'.join(rows[0].keys()))
            for row in rows:
                write('|'.join(map(str, row.values())))
        except:
            write('exception while executing command')
            write('type: %s  value: %s' % tuple(sys.exc_info()[:2]))
        cl = None
        write('')
        write('')
        write('DONE in %s seconds' % long(time.time() - start))
        out.write(str(footer))
    def testDataSourceAgainstDevice(self, testDevice, REQUEST, write, errorLog):
        """
        Does the majority of the logic for testing a datasource against the device
        @param string testDevice The id of the device we are testing
        @param Dict REQUEST the browers request
        @param Function write The output method we are using to stream the result of the command
        @parma Function errorLog The output method we are using to report errors
        """ 
        def writeLines(lines):
            for line in lines.splitlines():
                write(line)

        out = REQUEST.RESPONSE
        # Determine which device to execute against
        device = None
        if testDevice:
            # Try to get specified device
            device = self.findDevice(testDevice)
            if not device:
                errorLog(
                    'No device found',
                    'Cannot find device matching %s.' % testDevice,
                    priority=messaging.WARNING
                )
                return self.callZenScreen(REQUEST)
        elif hasattr(self, 'device'):
            # ds defined on a device, use that device
            device = self.device()
        elif hasattr(self, 'getSubDevicesGen'):
            # ds defined on a device class, use any device from the class
            try:
                device = self.getSubDevicesGen().next()
            except StopIteration:
                # No devices in this class, bail out
                pass
        if not device:
            errorLog(
                'No Testable Device',
                'Cannot determine a device against which to test.',
                priority=messaging.WARNING
            )
            return self.callZenScreen(REQUEST)
        ttpc = getattr(self.rrdTemplate(), 'targetPythonClass', '')
        from ZenPacks.community.SQLDataSource.SQLClient import SQLClient
        cl = SQLClient(device)
        try:
            ccm, ccn = ttpc.rsplit('.', 1)
            compClass = getattr(__import__(ttpc,globals(),locals(),[ccn]),ccn)
            if compClass:
                for comp in device.getMonitoredComponents():
                    if isinstance(comp, compClass):
                        device = comp
                        break
        except: pass
        header = ''
        footer = ''
        # Render
        if REQUEST.get('renderTemplate', True):
            header, footer = self.commandTestOutput().split('OUTPUT_TOKEN')

        out.write(str(header))

        start = time.time()
        try:
            sql, sqlp, kbs, cs = self.getQueryInfo(device)
            if not sql: raise StandardError('query is empty')
            sql = sql.replace('$','\\$')
            properties = dict([(
                        dp.getAliasNames() and dp.getAliasNames()[0] or dp.id,
                        dp.id) for dp in self.getRRDDataPoints()])
            write('Executing query: "%s"'%sql)
            write('')
            rows = cl.query({'t':(sql, {}, cs, properties)}).get('t', [{}])
            write('|'.join(rows[0].keys()))
            for row in rows:
                write('|'.join(map(str, row.values())))
        except:
            write('exception while executing command')
            write('type: %s  value: %s' % tuple(sys.exc_info()[:2]))
        cl.close()
        cl = None
        write('')
        write('')
        write('DONE in %s seconds' % long(time.time() - start))
        out.write(str(footer))