Ejemplo n.º 1
0
 def talesEvalAttrs(self, obj_attrs, **kwargs):
     for attr in obj_attrs:
         if isinstance(obj_attrs[attr], list):
             obj_attrs[attr] = [
                 talesEvalStr(x, self, extra=kwargs)
                 for x in obj_attrs[attr]
             ]
         else:
             obj_attrs[attr] = talesEvalStr(obj_attrs[attr],
                                            self,
                                            extra=kwargs)
    def getGraphElements(self, template, context, gopts, namespace, color,
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)
        if not color.startswith('#'):
            color = '#%s' % color
        pointval = self.pointval
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

            try:
                pointval = rpneval(pointval, rpn)
            except:
                pointval= 0
                self.raiseRPNExc()

        result = []
        if pointval:
            result += [ "COMMENT:%s(%s)\\j" % (self.SeverityString , pointval),
                ]
        log.warn(gopts + result)
        return gopts + result
Ejemplo n.º 3
0
def processTalSource(source, **kwargs):
    """
    This function is used to parse fields made available to actions that allow
    for TAL expressions.
    """
    if not kwargs.get('dev'):
        hasDevReference = re.search(DEVICE_TAL, source)
        if hasDevReference:
            attributes = hasDevReference.groups()
            log.error(
                "The TALES string '%s' references ${dev/xxx} %s,"
                " but no Zenoss device exists (use ${evt/xxx} fields instead?)",
                source, attributes)
            message = NO_ZEN_DEVICE % source
            raise TalesMissingZenossDevice(message)

    try:
        sourceStr = source
        context = kwargs.get('here')
        return talesEvalStr(sourceStr, context, kwargs)
    except CompilerError as ex:
        message = "%s: %s" % (ex, source)
        log.error("%s context = %s data = %s", message, context, kwargs)
        raise BadTalesExpresssion(message)
    except InvalidTalesException:
        message = BAD_TALES % source
        log.error("%s context = %s data = %s", message, context, kwargs)
        raise BadTalesExpresssion(message)
Ejemplo n.º 4
0
    def getTags(self, context):
        """Return dict of evaluated tags for given context.

        This includes tags that are the result of setting the store, forward,
        and other properties that should influence the metric tags for this
        datapoint.

        """
        tags = {}

        if self.store is False:
            tags[NO_STORE_KEY] = TRUTH_STRING

        if self.forward is False:
            tags[NO_FORWARD_KEY] = TRUTH_STRING

        if not self.tags:
            return tags

        # We may not need extra context. So don't get it yet.
        extra_context = None

        if isinstance(self.tags, types.StringTypes):
            lines = self.tags.splitlines()
        elif isinstance(self.tags, list):
            lines = itertools.chain.from_iterable(x.splitlines()
                                                  for x in self.tags)
        else:
            log.warning("tags not a string or list for %s",
                        context.getPrimaryId())

            return tags

        for line in lines:
            if not line:
                continue

            if "${" in line:
                # Get the context once now that we know we need it.
                extra_context = extra_context or self.getExtraContext(context)

                try:
                    line = talesEvalStr(line, context, extra=extra_context)
                except Exception as e:
                    log.warning("failed evaluating tag %r for %s: %s", line,
                                context.getPrimaryId(), e)

                    continue

            try:
                key, value = line.split(":", 1)
            except Exception:
                log.warning("failed getting key:value from tag %r for %s",
                            line, context.getPrimaryId())

                continue

            tags[key.strip()] = value.strip()

        return tags
Ejemplo n.º 5
0
def processTalSource(source, **kwargs):
    """
    This function is used to parse fields made available to actions that allow
    for TAL expressions.
    """
    if not kwargs.get('dev'):
        hasDevReference = re.search(DEVICE_TAL, source)
        if hasDevReference:
            attributes = hasDevReference.groups()
            log.error("The TALES string '%s' references ${dev/xxx} %s,"
                          " but no Zenoss device exists (use ${evt/xxx} fields instead?)",
                          source, attributes)
            message = NO_ZEN_DEVICE % source
            raise TalesMissingZenossDevice(message)

    try:
        sourceStr = source
        context = kwargs.get('here')
        return talesEvalStr(sourceStr, context, kwargs)
    except CompilerError as ex:
        message = "%s: %s" % (ex, source)
        log.error("%s context = %s data = %s", message, context, kwargs)
        raise BadTalesExpresssion(message)
    except InvalidTalesException:
        message = BAD_TALES % source
        log.error("%s context = %s data = %s", message, context, kwargs)
        raise BadTalesExpresssion(message)
Ejemplo n.º 6
0
    def getGraphElements(self, template, context, gopts, namespace, color,
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)
        if not color.startswith('#'):
            color = '#%s' % color
        pointval = self.pointval
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

            try:
                pointval = rpneval(pointval, rpn)
            except:
                pointval = 0
                self.raiseRPNExc()

        result = []
        if pointval:
            result += [
                "COMMENT:%s(%s)\\j" % (self.SeverityString, pointval),
            ]
        log.warn(gopts + result)
        return gopts + result
Ejemplo n.º 7
0
 def talesEval(self, str, context, **kw):
     '''
     return a tales evaluation of str
     '''
     from Products.ZenUtils.ZenTales import talesEvalStr
     extraContext = self.getTalesContext(thing=context, **kw)
     try:
         result = talesEvalStr(str, context, extraContext)
     except Exception:
         result = '(Tales expression error)'
     return result
    def talesEval(self, text, context):
        device = context.device()
        extra = {
            'device': device,
            'dev': device,
            'devname': device.id,
            'datasource': self,
            'ds': self,
            }

        return talesEvalStr(str(text), context, extra=extra)
	def talesEval(self, text, context):
		device = context.device()
		extra = {
			'device': device,
			'dev': device,
			'devname': device.id,
			'datasource': self,
			'ds': self,
			}

		return talesEvalStr(str(text), context, extra=extra)
    def windows_servername(self):
        """Return Windows server name for this device."""
        pname = 'zWinRMServerName'
        pvalue = self.getProperty(pname)
        if pvalue:
            try:
                return talesEvalStr(pvalue, self)
            except Exception:
                LOG.warn("%s.%s contains invalid TALES expression: %s",
                         self.id, pname, pvalue)

        # Fall back to an empty string.
        return ''
    def windows_servername(self):
        """Return Windows server name for this device."""
        pname = 'zWinRMServerName'
        pvalue = self.getProperty(pname)
        if pvalue:
            try:
                return talesEvalStr(pvalue, self)
            except Exception:
                LOG.warn(
                    "%s.%s contains invalid TALES expression: %s",
                    self.id, pname, pvalue)

        # Fall back to an empty string.
        return ''
Ejemplo n.º 12
0
    def getEventFields(self, context):
        """
        Add these fields to any resulting threshold event generated on the daemon.

        @paramter context: device or component object
        @type context: device or component object
        @returns: static event fields + values
        @rtype: dictionary
        """
        fields = {}
        for key in ('description', 'explanation', 'resolution'):
            value = getattr(self, key, None)
            if value:
                fields[key] = talesEvalStr(value, context)
        return fields
Ejemplo n.º 13
0
    def getEventFields(self, context):
        """
        Add these fields to any resulting threshold event generated on the daemon.

        @paramter context: device or component object
        @type context: device or component object
        @returns: static event fields + values
        @rtype: dictionary
        """
        fields = {}
        for key in ('description', 'explanation', 'resolution'):
            value = getattr(self, key, None)
            if value:
                fields[key] = talesEvalStr(value, context)
        return fields
Ejemplo n.º 14
0
 def evaluate(self, context):
     """
     Evaluate the formula with the given context so that the resulting
     rpn can be applied to the datapoint value.  There are two possible
     layers of evaluation: python and then TALES evaluation.  Both use the
     name 'here' to name the passed context.  See testRRDDataPointAlias
     for examples of usage.
     """
     if self.formula:
         formula = self.formula
         if formula.startswith(EVAL_KEY):
             formula = formula[len(EVAL_KEY):]
             formula = str(eval(formula, {'here': context}))
         return talesEvalStr(formula, context)
     else:
         return None
Ejemplo n.º 15
0
 def evaluate(self, context):
     """
     Evaluate the formula with the given context so that the resulting
     rpn can be applied to the datapoint value.  There are two possible
     layers of evaluation: python and then TALES evaluation.  Both use the
     name 'here' to name the passed context.  See testRRDDataPointAlias
     for examples of usage.
     """
     if self.formula:
         formula = self.formula
         if formula.startswith(EVAL_KEY):
             formula = formula[len(EVAL_KEY):]
             formula = str(eval(formula, {'here': context}))
         return talesEvalStr(formula, context)
     else:
         return None
    def getGraphElements(self, template, context, gopts, namespace, color,
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)

        if not color.startswith('#'):
            color = '#%s' % color
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

        result = []
        for dp in self.dataPointNames:
            # Convert the rrd to a Holt-Winters if it hasn't already been done
            ApplyHoltData(self.context().path(dp))

            # Retune the dp rrd file
            try:
                self.TuneHoltData(dp)
            except:
                pass

            result += [ "DEF:%sa=%s:ds0:AVERAGE" % (dp, self.context().path(dp)) ]
            result += [ "DEF:%sb=%s:ds0:HWPREDICT" % (dp, self.context().path(dp)) ]
            result += [ "DEF:%sc=%s:ds0:DEVPREDICT" % (dp, self.context().path(dp)) ]
            result += [ "DEF:%sd=%s:ds0:FAILURES" % (dp, self.context().path(dp)) ]
            result += [ "CDEF:%scdefc=%sb,%sc,%s,*,+" % (dp,dp,dp,self.delta) ]
            result += [ "CDEF:%scdefd=%sb,%sc,%s,*,-" % (dp,dp,dp,self.delta) ]
            result += [ "TICK:%sd%s:1.0:%s Failures\j" %
                    (dp,self.tkcolor,legend) ]
            result += [ "LINE3:%sb%s:%s HwPredict\j" %
                    (dp,self.predcolor,legend) ]
            result += [ "LINE2:%scdefc%s:%s Confidence Band\j" %
                    (dp,self.cbcolor,legend) ] # Upper confidence Band
            result += [ "LINE2:%scdefd%s:" % (dp,self.cbcolor) ] # Lower confidence band
            result += [ "LINE1:%sd#000000FF:" % dp ]
        return gopts + result
Ejemplo n.º 17
0
    def getGraphElements(self, template, context, gopts, namespace, color,
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)
        if not color.startswith('#'):
            color = '#%s' % color
        minval = self.minimum
        maxval = self.maximum
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

            try:
                minval = rpneval(minval, rpn)
            except:
                minval= 0
                self.raiseRPNExc()

            try:
                maxval = rpneval(maxval, rpn)
            except:
                maxval= 0
                self.raiseRPNExc()

        result = []
        if minval:
            result += [
                "HRULE:%s%s:%s\\j" % (minval, color,
                          legend or self.getMinLabel(minval, relatedGps)),
                ]
        if maxval:
            result += [
                "HRULE:%s%s:%s\\j" % (maxval, color,
                          legend or self.getMaxLabel(maxval, relatedGps))
                ]
        return gopts + result
Ejemplo n.º 18
0
    def getGraphElements(self, template, context, gopts, namespace, color,
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)
        if not color.startswith('#'):
            color = '#%s' % color
        minval = self.minimum
        maxval = self.maximum
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

            try:
                minval = rpneval(minval, rpn)
            except:
                minval = 0
                self.raiseRPNExc()

            try:
                maxval = rpneval(maxval, rpn)
            except:
                maxval = 0
                self.raiseRPNExc()

        result = []
        if minval:
            result += [
                "HRULE:%s%s:%s\\j" % (minval, color, legend
                                      or self.getMinLabel(minval, relatedGps)),
            ]
        if maxval:
            result += [
                "HRULE:%s%s:%s\\j" %
                (maxval, color, legend or self.getMaxLabel(maxval, relatedGps))
            ]
        return gopts + result
Ejemplo n.º 19
0
    def getGraphValues(self, relatedGps, context):
        """
        Returns the values that we want to include for the
        visualization of this threshold. For a minmax we simply
        display lines representing the minval and maxval.
        """
        minval = self.minimum
        if minval is None or minval == '':
            minval = NaN
        maxval = self.maximum
        if maxval is None or maxval == '':
            maxval = NaN
        if not self.dataPointNames:
            return []
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except Exception as e:
                log.exception(e)
                self.raiseRPNExc()
                return []

            try:
                if minval is not NaN:
                    minval = rpneval(minval, rpn)
            except Exception:
                minval = 0
                self.raiseRPNExc()

            try:
                if maxval is not NaN:
                    maxval = rpneval(maxval, rpn)
            except Exception:
                maxval = 0
                self.raiseRPNExc()

        minval = nanToNone(minval)
        maxval = nanToNone(maxval)
        return [minval, maxval]
Ejemplo n.º 20
0
    def __init__(self, *args, **kwargs):
        # original is injected into locals by the monkeypatch decorator.
        original(self, *args, **kwargs)

        # Reset cmdmap and _commands.
        self.cmdmap = {}
        self._commands = []

        # Get plugins from args or kwargs.
        plugins = kwargs.get('plugins')
        if plugins is None:
            if len(args) > 3:
                plugins = args[3]
            else:
                plugins = []

        # Get device from args or kwargs.
        device = kwargs.get('device')
        if device is None:
            if len(args) > 5:
                device = args[5]
            else:
                device = None

        # Do TALES evaluation of each plugin's command.
        for plugin in plugins:
            if re.search(r'\$\{\S+\/\S+\}', plugin.command):
                try:
                    command = talesEvalStr(plugin.command, device)
                except Exception:
                    CollectorClient.log.exception(
                        '%s - command TALES evaluation failed, proceeding',
                        device.id)

                    command = plugin.command
            else:
                command = plugin.command

            self.cmdmap[command] = plugin
            self._commands.append(command)
Ejemplo n.º 21
0
    def getGraphValues(self, relatedGps, context):
        """
        Returns the values that we want to include for the
        visualization of this threshold. For a minmax we simply
        display lines representing the minval and maxval.
        """
        minval = self.minimum
        if minval is None or minval == '':
            minval = NaN
        maxval = self.maximum
        if maxval is None or maxval == '':
            maxval = NaN
        if not self.dataPointNames:
            return []
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except Exception, e:
                log.exception(e)
                self.raiseRPNExc()
                return []

            try:
                if minval is not NaN:
                    minval = rpneval(minval, rpn)
            except:
                minval= 0
                self.raiseRPNExc()

            try:
                if maxval is not NaN:
                    maxval = rpneval(maxval, rpn)
            except:
                maxval= 0
                self.raiseRPNExc()
    def getGraphElements(self, template, context, gopts, namespace, color, 
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)
        if not color.startswith('#'):
            color = '#%s' % color
        minval = self.minimum
        if minval is None or minval == '':
            minval = NaN
        maxval = self.maximum
        if maxval is None or maxval == '':
            maxval = NaN
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

            try:
                minval = rpneval(minval, rpn)
            except:
                minval= 0
                self.raiseRPNExc()

            try:
                maxval = rpneval(maxval, rpn)
            except:
                maxval= 0
                self.raiseRPNExc()
        
        minstr = self.setPower(minval)
        maxstr = self.setPower(maxval)

        minval = nanToNone(minval)
        maxval = nanToNone(maxval)
        if legend:
            gopts.append(
                "HRULE:%s%s:%s\\j" % (minval or maxval, color, legend))
        elif minval is not None and maxval is not None:
            if minval == maxval:
                gopts.append(
                    "HRULE:%s%s:%s not equal to %s\\j" % (minval, color,
                        self.getNames(relatedGps), minstr))
            elif minval < maxval:
                gopts.append(
                    "HRULE:%s%s:%s not within %s and %s\\j" % (minval, color,
                        self.getNames(relatedGps), minstr, maxstr))
                gopts.append("HRULE:%s%s" % (maxval, color))
            elif minval > maxval:
                gopts.append(
                    "HRULE:%s%s:%s between %s and %s\\j" % (minval, color,
                        self.getNames(relatedGps), maxstr, minstr))
                gopts.append("HRULE:%s%s" % (maxval, color))
        elif minval is not None :
            gopts.append(
                "HRULE:%s%s:%s less than %s\\j" % (minval, color,
                    self.getNames(relatedGps), minstr))
        elif maxval is not None:
            gopts.append(
                "HRULE:%s%s:%s greater than %s\\j" % (maxval, color,
                    self.getNames(relatedGps), maxstr))

        return gopts
    def onSuccess(self, results, config):
        data = self.new_data()
        root = etree.Element('root')

        # Find and save the cluster tree
        for result in results[0]:
            tree = etree.parse(StringIO(result))
            root.append(tree.getroot())
            if tree.getroot().tag == 'clusters':
                cluster_tree = tree

        for result in results[0]:
            result_tree = etree.parse(StringIO(result))
            if result_tree.getroot().tag == 'storage_domains':
                count = len(result_tree.getroot().getchildren())
                addCount(root, [config.id], 'storagedomainCount', count)
            elif result_tree.getroot().tag == 'clusters':
                count = len(result_tree.getroot().getchildren())
                addCount(root, [config.id], 'clusterCount', count)
                data_centers = result_tree.xpath('//data_center/@id')
                addCount(root, data_centers, 'clusterCount')
            elif result_tree.getroot().tag == 'data_centers':
                count = len(result_tree.getroot().getchildren())
                addCount(root, [config.id], 'datacenterCount', count)
            elif result_tree.getroot().tag == 'hosts':
                count = len(result_tree.getroot().getchildren())
                addCount(root, [config.id], 'hostCount', count)
                clusters = result_tree.xpath('//cluster/@id')
                addCount(root, clusters, 'hostCount')

                for cluster in clusters:
                    datacenter = cluster_tree.xpath('//cluster[@id="%s"]/data_center/@id' % cluster)
                    addCount(root, datacenter, 'hostCount', 1)

            elif result_tree.getroot().tag == 'vms':
                count = len(result_tree.getroot().getchildren())
                addCount(root, [config.id], 'vmCount', count)
                clusters = result_tree.xpath('//cluster/@id')
                addCount(root, clusters, 'vmCount')

                hosts = result_tree.xpath('//host/@id')
                addCount(root, hosts, 'vmCount')

                for cluster in clusters:
                    datacenter = cluster_tree.xpath('//cluster[@id="%s"]/data_center/@id' % cluster)
                    addCount(root, datacenter, 'vmCount', 1)

        for result_stat in results[1]:
            root.append(etree.parse(StringIO(result_stat)).getroot())
            # This is the general format ...
            #root.xpath('//*[*/@id="368bf44e-7d29-483a-8c2e-9a79962b1e48"][name/text()="disk.read.latency"]/values/value/datum/text()')[0]

        for ds in config.datasources:
            if ds.component:
                component_id = prepId(ds.component)
            else:
                component_id = None

            for point in ds.points:
                # Handle percentage custom datapoints
                if "ovirt:" in point.xpath and point.rpn and 'xpath' in ds.params:
                    resultsDict = {}
                    try:
                        xpath = talesEvalStr(ds.params['xpath'], context=None, extra=ds.params['context'])
                        statdata = [(x.xpath('name/text()'), x.xpath('values/value/datum/text()')) for x in root.xpath(xpath) if x.tag == 'statistic']
                        for item, val in statdata:
                            resultsDict[item[0]] = val[0]
                        rpnstring = talesEvalStr(point.rpn, context=None, extra={'here': resultsDict})
                        results = rpneval(rpnstring.split(',', 1)[0], rpnstring.split(',', 1)[1])
                        data['values'][component_id][point.id] = (results, 'N')
                    except Exception:
                        pass

                # Do the rest using xpath
                elif 'xpath' in ds.params:
                    try:
                        # Some points may not exist in the xml, skip those...
                        xpath = talesEvalStr(ds.params['xpath'], context=None, extra=ds.params['context'])

                        results = root.xpath(xpath+point.xpath)
                        if 'Count' in point.xpath and not results:
                            results = ['0']
                        results = results[0]

                        # If rpn is defined, lets calculate the new results.
                        if point.rpn:
                            results = rpneval(
                                results, talesEvalStr(point.rpn, context=None, extra=ds.params['context']))
                        data['values'][component_id][point.id] = (results, 'N')
                    except Exception:
                        pass
        data['events'].append({
            'eventClassKey': 'oVirtCollectionSuccess',
            'eventKey': eventKey(config),
            'summary': 'ovirt: successful collection',
            'eventClass': '/Status/Perf/',
            'device': config.id,
            'severity': 0,
        })
        return data
 def talesEvalAttrs(self, obj_attrs, **kwargs):
     for attr in obj_attrs:
         if isinstance(obj_attrs[attr], list):
             obj_attrs[attr] = [talesEvalStr(x, self, extra=kwargs) for x in obj_attrs[attr]]
         else:
             obj_attrs[attr] = talesEvalStr(obj_attrs[attr], self, extra=kwargs)
Ejemplo n.º 25
0
    def getGraphElements(self, template, context, gopts, namespace, color, 
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)
        if not color.startswith('#'):
            color = '#%s' % color
        minval = self.minimum
        if minval is None:
            minval = NaN
        maxval = self.maximum
        if maxval is None:
            maxval = NaN
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

            try:
                minval = rpneval(minval, rpn)
            except:
                minval= 0
                self.raiseRPNExc()

            try:
                maxval = rpneval(maxval, rpn)
            except:
                maxval= 0
                self.raiseRPNExc()

        minstr = self.setPower(minval)
        maxstr = self.setPower(maxval)

        minval = nanToNone(minval)
        maxval = nanToNone(maxval)
        if legend:
            gopts.append(
                "HRULE:%s%s:%s\\j" % (minval or maxval, color, legend))
        elif minval is not None and maxval is not None:
            if minval == maxval:
                gopts.append(
                    "HRULE:%s%s:%s not equal to %s\\j" % (minval, color,
                        self.getNames(relatedGps), minstr))
            elif minval < maxval:
                gopts.append(
                    "HRULE:%s%s:%s not within %s and %s\\j" % (minval, color,
                        self.getNames(relatedGps), minstr, maxstr))
                gopts.append("HRULE:%s%s" % (maxval, color))
            elif minval > maxval:
                gopts.append(
                    "HRULE:%s%s:%s between %s and %s\\j" % (minval, color,
                        self.getNames(relatedGps), maxstr, minstr))
                gopts.append("HRULE:%s%s" % (maxval, color))
        elif minval is not None :
            gopts.append(
                "HRULE:%s%s:%s less than %s\\j" % (minval, color,
                    self.getNames(relatedGps), minstr))
        elif maxval is not None:
            gopts.append(
                "HRULE:%s%s:%s greater than %s\\j" % (maxval, color,
                    self.getNames(relatedGps), maxstr))

        return gopts
 def talesEvalStr(self, value, **kwargs):
     if value.startswith("python:"):
         return talesEval(value, self, extra=kwargs)
     else:
         return talesEvalStr(value, self, extra=kwargs)
 def talesEvalStr(self, value, **kwargs):
     if value.startswith("python:"):
         return talesEval(value, self, extra=kwargs)
     else:
         return talesEvalStr(value, self, extra=kwargs)
 def talesEvalStr(self, value, **kwargs):
     return talesEvalStr(value, self, extra=kwargs)
Ejemplo n.º 29
0
    def getGraphElements(self, template, context, gopts, namespace, color,
                         legend, relatedGps):
        """Produce a visual indication on the graph of where the
        threshold applies."""
        unused(template, namespace)

        if not color.startswith('#'):
            color = '#%s' % color
        if not self.dataPointNames:
            return gopts
        gp = relatedGps[self.dataPointNames[0]]

        # Attempt any RPN expressions
        rpn = getattr(gp, 'rpn', None)
        if rpn:
            try:
                rpn = talesEvalStr(rpn, context)
            except:
                self.raiseRPNExc()
                return gopts

        result = []
        for dp in self.dataPointNames:
            # Convert the rrd to a Holt-Winters if it hasn't already been done
            ApplyHoltData(self.context().path(dp))

            # Retune the dp rrd file
            try:
                self.TuneHoltData(dp)
            except:
                pass

            result += [
                "DEF:%sa=%s:ds0:AVERAGE" % (dp, self.context().path(dp))
            ]
            result += [
                "DEF:%sb=%s:ds0:HWPREDICT" % (dp, self.context().path(dp))
            ]
            result += [
                "DEF:%sc=%s:ds0:DEVPREDICT" % (dp, self.context().path(dp))
            ]
            result += [
                "DEF:%sd=%s:ds0:FAILURES" % (dp, self.context().path(dp))
            ]
            result += [
                "CDEF:%scdefc=%sb,%sc,%s,*,+" % (dp, dp, dp, self.delta)
            ]
            result += [
                "CDEF:%scdefd=%sb,%sc,%s,*,-" % (dp, dp, dp, self.delta)
            ]
            result += [
                "TICK:%sd%s:1.0:%s Failures\j" % (dp, self.tkcolor, legend)
            ]
            result += [
                "LINE3:%sb%s:%s HwPredict\j" % (dp, self.predcolor, legend)
            ]
            result += [
                "LINE2:%scdefc%s:%s Confidence Band\j" %
                (dp, self.cbcolor, legend)
            ]  # Upper confidence Band
            result += ["LINE2:%scdefd%s:" % (dp, self.cbcolor)
                       ]  # Lower confidence band
            result += ["LINE1:%sd#000000FF:" % dp]
        return gopts + result
Ejemplo n.º 30
0
 def talesEvalStr(self, value, **kwargs):
     return talesEvalStr(value, self, extra=kwargs)
Ejemplo n.º 31
0
    def _datasources(self, deviceOrComponent, deviceId, componentId, collector):
        for template in deviceOrComponent.getRRDTemplates():

            # Get all enabled datasources that are PythonDataSource or
            # subclasses thereof.
            datasources = [
                ds for ds in template.getRRDDataSources() \
                    if ds.enabled and isinstance(ds, PythonDataSource)]

            device = deviceOrComponent.device()

            for ds in datasources:
                datapoints = []

                try:
                    ds_plugin_class = ds.getPluginClass()
                except Exception as e:
                    log.error(
                        "Failed to load plugin %r for %s/%s: %s",
                        ds.plugin_classname,
                        template.id,
                        ds.titleOrId(),
                        e)

                    continue

                for dp in ds.datapoints():
                    dp_config = DataPointConfig()
                    dp_config.id = dp.id
                    dp_config.dpName = dp.name()
                    dp_config.component = componentId
                    dp_config.rrdPath = '/'.join((deviceOrComponent.rrdPath(), dp.name()))
                    dp_config.rrdType = dp.rrdtype
                    dp_config.rrdCreateCommand = dp.getRRDCreateCommand(collector)
                    dp_config.rrdMin = dp.rrdmin
                    dp_config.rrdMax = dp.rrdmax

                    # MetricMixin.getMetricMetadata() added in Zenoss 5.
                    if hasattr(deviceOrComponent, 'getMetricMetadata'):
                        dp_config.metadata = deviceOrComponent.getMetricMetadata()

                    # Attach unknown properties to the dp_config
                    for key in dp.propdict().keys():
                        if key in known_point_properties:
                            continue
                        try:
                            value = getattr(dp, key)
                            if isinstance(value, basestring) and '$' in value:
                                extra = {
                                    'device': device,
                                    'dev': device,
                                    'devname': device.id,
                                    'datasource': ds,
                                    'ds': ds,
                                    'datapoint': dp,
                                    'dp': dp,
                                    }

                                value = talesEvalStr(
                                    value,
                                    deviceOrComponent,
                                    extra=extra)

                            setattr(dp_config, key, value)
                        except Exception:
                            pass

                    datapoints.append(dp_config)

                ds_config = PythonDataSourceConfig()
                ds_config.device = deviceId
                ds_config.manageIp = deviceOrComponent.getManageIp()
                ds_config.component = componentId
                ds_config.plugin_classname = ds.plugin_classname
                ds_config.template = template.id
                ds_config.datasource = ds.titleOrId()
                ds_config.config_key = ds.getConfigKey(deviceOrComponent)
                ds_config.params = ds.getParams(deviceOrComponent)
                ds_config.cycletime = ds.getCycleTime(deviceOrComponent)
                ds_config.eventClass = ds.eventClass
                ds_config.eventKey = ds.eventKey
                ds_config.severity = ds.severity
                ds_config.points = datapoints

                # Populate attributes requested by plugin.
                for attr in ds_plugin_class.proxy_attributes:
                    value = getattr(deviceOrComponent, attr, None)
                    if callable(value):
                        value = value()

                    setattr(ds_config, attr, value)

                yield ds_config
Ejemplo n.º 32
0
    def getTags(self, context):
        """Return dict of evaluated tags for given context.

        This includes tags that are the result of setting the store, forward,
        and other properties that should influence the metric tags for this
        datapoint.

        """
        tags = {}

        if self.store is False:
            tags[NO_STORE_KEY] = TRUTH_STRING

        if self.forward is False:
            tags[NO_FORWARD_KEY] = TRUTH_STRING

        if not self.tags:
            return tags

        # We may not need extra context. So don't get it yet.
        extra_context = None

        if isinstance(self.tags, types.StringTypes):
            lines = self.tags.splitlines()
        elif isinstance(self.tags, list):
            lines = itertools.chain.from_iterable(
                x.splitlines() for x in self.tags)
        else:
            log.warning(
                "tags not a string or list for %s",
                context.getPrimaryId())

            return tags

        for line in lines:
            if not line:
                continue

            if "${" in line:
                # Get the context once now that we know we need it.
                extra_context = extra_context or self.getExtraContext(context)

                try:
                    line = talesEvalStr(line, context, extra=extra_context)
                except Exception as e:
                    log.warning(
                        "failed evaluating tag %r for %s: %s",
                        line,
                        context.getPrimaryId(),
                        e)

                    continue

            try:
                key, value = line.split(":", 1)
            except Exception:
                log.warning(
                    "failed getting key:value from tag %r for %s",
                    line,
                    context.getPrimaryId())

                continue

            tags[key.strip()] = value.strip()

        return tags