示例#1
0
    def command(self, opts, pattern):
        """Disable check bundles based on pattern

        Note: if you want to disable only some metrics for a check, use the
        disable_metrics command instead.

        Arguments:
            pattern     --  search pattern for checks
        """
        checks, groups = util.find_checks(self.api, pattern)
        if not checks:
            log.error("No matching checks found\n" % check_id)
            return

        print "Disabling the following check bundles: "
        bundle_ids = {}
        for c in checks:
            if c['bundle_id'] not in bundle_ids:
                print "    %s" % c['name']
                bundle_ids[c['bundle_id']] = c['name']

        if util.confirm():
            for c in bundle_ids:
                log.msg("Disabling %s" % bundle_ids[c])
                self.api.disable_check_bundle(bundle_id=c)
示例#2
0
    def command(self, opts, pattern, *metrics_to_enable):
        """Activate metrics for checks

        Arguments:
            pattern             -- Pattern for checks
            metrics_to_enable   -- List of metrics to enable
        """
        checks, groups = util.find_checks(self.api, pattern)
        already_enabled = {}

        # Pick only one check per check bundle
        bundles = {}
        for c in checks:
            if c['bundle_id'] in bundles:
                continue
            bundles[c['bundle_id']] = c

        log.msg("Retrieving metrics for checks")
        count = 0
        for c in bundles.values():
            count += 1
            print "\r%s/%s" % (count, len(bundles)),
            sys.stdout.flush()
            rv = self.api.list_metrics(check_id=c['check_id'])
            already_enabled[c['check_id']] = []
            for metric in sorted(rv):
                if metric['enabled']:
                    already_enabled[c['check_id']].append(metric['name'])

        log.msg("Metrics to enable: %s" % (', '.join(metrics_to_enable)))
        log.msg("About to enable metrics for the following checks")
        for c in bundles.values():
            log.msg("    %s (%s)" % (c['name'],
                ', '.join(already_enabled[c['check_id']])))

        if util.confirm():
            for c in bundles.values():
                # Enable metrics here
                log.msgnb("%s..." % c['name'])
                all_metrics = set(already_enabled[c['check_id']]) \
                    | set(metrics_to_enable)
                if all_metrics != set(already_enabled[c['check_id']]):
                    # The set of metrics has changed, apply the edit
                    self.api.edit_check_bundle(
                        bundle_id=c['bundle_id'],
                        metric_name=list(all_metrics))
                    log.msgnf("Done")
                else:
                    log.msgnf("No changes")
示例#3
0
    def command(self, opts, pattern, *metrics_to_enable):
        """Set the active metrics for a check based on regular expression

        This command will set the enabled metrics to exactly what matches the
        pattern(s) given. Any other metrics will be disabled, regardless of
        what their original setting was.

        Arguments:
            pattern             -- Pattern for checks
            metrics_to_enable   -- One or more regexes for enabled metrics
        """
        checks, groups = util.find_checks(self.api, pattern)
        to_enable = {}

        # Pick only one check per check bundle
        bundles = {}
        for c in checks:
            if c['bundle_id'] in bundles:
                continue
            bundles[c['bundle_id']] = c

        log.msg("Retrieving metrics for checks")
        count = 0
        for c in bundles.values():
            count += 1
            print "\r%s/%s" % (count, len(bundles)),
            sys.stdout.flush()
            rv = self.api.list_available_metrics(check_id=c['check_id'])
            to_enable[c['check_id']] = []
            for mtype in rv['metrics']:
                for metric in rv['metrics'][mtype]:
                    for pattern in metrics_to_enable:
                        if re.match(pattern, metric):
                            to_enable[c['check_id']].append(metric)

        log.msg("About to set enabled metrics for the following checks")
        for c in bundles.values():
            log.msg("    %s (%s)" % (c['name'],
                ', '.join(sorted(to_enable[c['check_id']]))))

        if util.confirm():
            for c in bundles.values():
                # Enable metrics here
                log.msgnb("%s..." % c['name'])
                # The set of metrics has changed, apply the edit
                self.api.edit_check_bundle(
                    bundle_id=c['bundle_id'],
                    metric_name=to_enable[c['check_id']])
                log.msgnf("Done")
示例#4
0
    def command(self, opts, check_pattern, metric_pattern):
        """List active metrics, optionally disabling them

        Note: if you want to disable all metrics for a check, use the
        disable_checks command instead.

        Options:
            -d - disable the metrics

        Arguments:
            check_pattern     --  search pattern for checks
            metric_pattern    --  search pattern for metrics
        """
        checks, groups = util.find_checks(self.api, check_pattern)
        if not checks:
            log.error("No matching checks found\n" % check_id)
            return
        to_remove = {}
        to_keep = {}
        check_names = {}
        bundle_names = {}
        for c in checks:
            check_names[c['check_id']] = c['name']
            bundle_names[c['bundle_id']] = c['name']
            matching_metrics, non_matching_metrics = util.find_metrics(
                    self.api, c['check_id'], metric_pattern)
            if matching_metrics:
                to_remove[c['check_id']] = matching_metrics
                to_keep[c['bundle_id']] = non_matching_metrics
                print non_matching_metrics

        print "Disabling the following metrics: "
        for c in sorted(to_remove):
            print "    %s" % check_names[c]
            for m in to_remove[c]:
                print "        %s" % m['name']

        if ('-d', '') in opts:
            if util.confirm():
                for c in to_keep:
                    log.msg("Disabling metrics for check: %s" %
                            bundle_names[c])
                    self.api.edit_check_bundle(bundle_id=c,
                            metric_name=[i['name'] for i in to_keep[c]])
示例#5
0
    def command(self, opts, check_pattern, metric_pattern=None):
        """Removes rules for checks that match the given pattern

        Arguments:
            check_pattern   -- regex to match check names on (optional)
            metric_pattern  -- regex to match metric names on (optional)

        At least one of check_pattern or metric_pattern must be provided. If
        you want to leave out the check_pattern, then specify it as an empty
        string.
        """
        rules = self.api.list_rules()

        if check_pattern and check_pattern != '.':
            checks, groups = util.find_checks(self.api, check_pattern)
            check_ids = dict([(c['check_id'], c['name']) for c in checks])
            matching = [r for r in rules if r['check_id'] in check_ids]
        else:
            checks = self.api.list_checks()
            check_ids = dict([(c['check_id'], c['name']) for c in checks])
            matching = rules

        if metric_pattern:
            matching = [r for r in matching if
                    re.search(metric_pattern, r['metric_name'])]

        matching = sorted(matching, reverse=True,
                key=lambda x: (x['check_id'], x['metric_name'], x['order']))
        log.msg("About to delete the following rules:")
        for r in matching:
            log.msg("%s`%s (%s - %s %s)" % (check_ids[r['check_id']],
                r['metric_name'], r['order'], r['criteria'], r['value']))
        if util.confirm():
            for r in matching:
                log.msgnb("Deleting %s`%s (%s)..." % (
                    check_ids[r['check_id']], r['metric_name'], r['order']))
                try:
                    rv = self.api.remove_metric_rule(check_id=r['check_id'],
                            metric_name=r['metric_name'], order=r['order'])
                    log.msgnf("Success")
                except circonusapi.CirconusAPIError, e:
                    log.msgnf("Failed")
                    log.error(e.error)
示例#6
0
    def command(self, opts, template_name, pattern):
        """Add graphs for multiple checks in bulk based on a template

        Arguments:
            template_name   -- the name of the template file
            pattern         -- a regex to match on check names

        The templates are in json, and is in the same format as the output of
        the dump_graph command.

        Various string subsitutions can be used:

        {check_id}     - The check ID
        {check_name}   - The check name
        {check_target} - The target of the check (IP address)
        {check_agent}  - The agent the check is run from
        {groupN}       - Matching groups (the parts in parentheses) in the
                         pattern given on the command line. (replace N with
                         a group number)

        You can also use named matching groups - (?P<groupname>...) in the
        pattern and {groupname} in the graph template.
        """
        try:
            template = util.GraphTemplate(template_name)
        except IOError:
            log.error("Unable to open template %s" % template_name)
            sys.exit(1)
        checks, groups = util.find_checks(self.api, pattern)
        util.verify_metrics(self.api, template, checks)
        log.msg("About to add %s graphs for the following checks:" % (
            template_name))
        for c in checks:
            log.msg("    %s (%s)" % (c['name'], c['agent']))
        if not util.confirm():
            log.msg("Not adding graphs.")
            sys.exit()
        self.add_graphs(template, checks, groups)
示例#7
0
    def command(self, opts, template_name, pattern, *params):
        """Adds rules for checks that match the given pattern

        Arguments:
            template_name   -- the name of the template file
            pattern         -- regex to match check names on
            params          -- other parameters (see below)

        Other parameters are specified as "param_name=value" and will
        be substituted in the template. Use {param_name} in the template.

        Some predefined parameters:
            {check_id}     - The check ID
            {check_name}   - The check name
            {check_target} - The target of the check (IP address)
            {check_agent}  - The agent the check is run from
            {groupN}       - Matching groups (the parts in parentheses) in the
                            pattern given on the command line. (replace N with
                            a group number)
        """
        template = util.RuleTemplate(template_name)
        template_params = template.parse_nv_params(params)
        checks, groups = util.find_checks(self.api, pattern)
        util.verify_metrics(self.api, template, checks)
        log.msg("About to add %s rules for the following checks:" % (template_name))
        for c in checks:
            log.msg("    %s (%s)" % (c["name"], c["agent"]))
        if not util.confirm():
            log.msg("Not adding rules.")
            sys.exit()

        for c in checks:
            p = {
                "check_name": c["name"],
                "check_id": c["check_id"],
                "check_target": c["target"],
                "check_agent": c["agent"],
            }
            p.update(template_params)
            p.update(groups[c["check_id"]])
            substituted = template.sub(p)

            # Get mapping from contact group name to ID
            rv = self.api.list_contact_groups()
            contact_group_ids = {}
            for i in rv:
                contact_group_ids[i["name"]] = i["contact_group_id"]
            for rule in substituted:
                # Extract the contact groups and get the IDs
                for severity in rule["contact_groups"]:
                    contact_group_names = rule["contact_groups"][severity]
                    del rule["contact_groups"][severity]
                    rule["contact_groups"][severity] = []
                    for cg in contact_group_names:
                        rule["contact_groups"][severity].append({"id": contact_group_ids[cg], "name": cg})

                log.msgnb("Adding rule for %s... " % c["name"])
                try:
                    rv = self.api.set_ruleset(ruleset=json.dumps(rule))
                    log.msgnf("Success")
                except circonusapi.CirconusAPIError, e:
                    log.msgnf("Failed")
                    log.error(e.error)