def collect(self, device, log):
     self.deferred = Deferred()
     cl = self._pool.get(device.id)
     if cl is None:
         cl = SQLClient(device, datacollector=self)
         self._pool[device.id] = cl
     cl.plugins.append(self)
     cl.run()
     return self.deferred
示例#2
0
 def collect(self, device, log):
     self.deferred = Deferred()
     cl = self._pool.get(device.id)
     if cl is None:
         cl = SQLClient(device, datacollector=self)
         self._pool[device.id] = cl
     cl.plugins.append(self)
     cl.run()
     return self.deferred
示例#3
0
 def collect(self, device, log):
     queries = self.queries(device)
     for tname, query in queries.iteritems():
         if len(query) == 3:
             cs, sql, columns = query
             if type(columns) is not dict:
                 columns = dict(zip(columns, columns))
         else:
             sql, kb, cs, columns = query
         queries[tname] = (sql, {}, "findodbc, '" + cs + "'", columns)
     return SQLClient(device).query(queries)
示例#4
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 collect(self, device, log):
     deferred = Deferred()
     cl = SQLClient(device, datacollector=self, plugins=[self])
     setattr(cl, 'deferred', deferred)
     cl.run()
     return deferred
    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))