Example #1
0
    def command(self, opts, template_name, target, agent, *params):
        """Adds a check based on a template

        Arguments:
            template_name   -- the name of the template file
            check_name      -- the name for the check
            target          -- the target of the check (can be a hostname)
            agent           -- the agent to run the check from
            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:

            {agent}         -- the agent provided on the command line
            {target}        -- the target provided on the command line
            {targetip}      -- the ip of the target resolved in dns
                               (may be same as target if target was provided
                                as an IP)
        """
        template = util.Template(template_name, "check")
        targetip = util.resolve_target(target)
        template_params = {
            'agent': agent,
            'target': target,
            'targetip': targetip}
        template_params.update(template.parse_nv_params(params))

        substituted = template.sub(template_params)
        # Add required parameters
        substituted['agent_id'] = util.get_agent(self.api, agent)
        substituted['target'] = targetip

        # Allow matching metrics by regex, find available metrics, and test
        # them against each regex in the metrics_regex key in the template to
        # see if they match.
        if 'metric_regex' in substituted:
            log.msg("Fetching available metrics for regex match")
            try:
                substituted['test_mode'] = 1
                rv = self.api.add_check_bundle(**substituted)
                del substituted['test_mode']
            except circonusapi.CirconusAPIError, e:
                log.error("Failed to fetch available metrics: %s" % e.error)
                sys.exit(1)
            available_metrics = rv['metrics']
            for metric_type in available_metrics:
                for m in available_metrics[metric_type]:
                    for regex in substituted['metric_regex']:
                        if re.match(regex, m):
                            substituted['metric_name'].append(m)
                            break
            log.msg("Metrics to include in the check:")
            for m in sorted(substituted['metric_name']):
                print "    %s" % m
Example #2
0
    def command(self, opts, template_type, template_name, *params):
        """Prints out a template with parameters substituted

        Arguments:
            template_type   -- the type of the template
            template_name   -- the name of the template file
            params          -- parameters (see below)

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

        If a 'target' parameter is given, then a 'targetip' parameter will
        be automatically provided and will resolve to the IP address pointed
        to by the target hostname (if it is a hostname).
        """
        template = util.Template(template_name, template_type)
        params = template.parse_nv_params(params)
        if 'target' in params:
            params['targetip'] = util.resolve_target(params['target'])

        substituted = template.sub(params)
        print json.dumps(substituted, indent=4)
Example #3
0
    def command(self, opts, target, agent, community, friendly_name,
            pattern=None):
        """Adds snmp checks for a switch

        This command queries the switch using snmpwalk to discover what ports
        to add checks for. This requires that the snmpwalk command be
        available and that the switch be accessible over snmp from the machine
        that this command is run from.

        Arguments:
            target          -- The address of the switch
            agent           -- The name of the agent you wish circonus to use
                               for the checks
            community       -- SNMP community for the switch
            friendly_name   -- what to call the switch in the check name. This
                               is usually the (short) hostname of the switch.
            pattern         -- An optional regex to limit which ports to add.
        """
        # TODO - abstract this away and prompt the user for a list of
        # available agents
        rv = self.api.list_agents()
        agents = dict([(i['name'], i['agent_id']) for i in rv])
        try:
            self.agent = agents[agent]
        except KeyError:
            log.error("Invalid/Unknown Agent: %s" % agent)
            sys.exit(1)
        self.target = util.resolve_target(target)
        self.community = community
        self.friendly_name = friendly_name
        self.ports = self.get_ports(target, community, pattern)
        log.msg("About to add checks for the following ports:")
        for port in sorted(self.ports):
            log.msg(port)
        if util.confirm():
            self.add_checks()
	def pretty(self, context: list[Team]) -> str:
		"""Get a human-readable representation of this transaction."""
		import util
		try:
			if self.name == "DamageTransaction":
				target = util.resolve_target(context, Target(**self.args["Target"]))
				status = StatusCondition(self.args["StatusEffect"])

				text = f"{target.pokemon.name_and_type} took **{self.args['Damage']} damage**."
				if status != 0:
					return text[:-1] + f" from being {status.past_tense}."
				else:
					return text
			elif self.name == "FriendshipTransaction":
				pkmn = util.resolve_target(context, Target(**self.args["Target"])).pokemon

				if self.args['Amount'] > 0:
					return f"{pkmn.name_and_type} friendship increased by {self.args['Amount']}."
				else:
					return f"{pkmn.name_and_type} friendship decreased by {abs(self.args['Amount'])}."
			elif self.name == "EVTransaction":
				pkmn = util.resolve_target(context, Target(**self.args["Target"])).pokemon
				stat = Stat(self.args['Stat'])

				return f"{pkmn.name_and_type} gained {self.args['Amount']} {stat} EVs."
			elif self.name == "HealTransaction":
				pkmn = util.resolve_target(context, Target(**self.args["Target"])).pokemon

				return f"{pkmn.name_and_type} restored {self.args['Amount']} HP."
			elif self.name == "InflictStatusTransaction":
				pkmn = util.resolve_target(context, Target(**self.args["Target"])).pokemon
				status = StatusCondition(self.args["StatusEffect"])

				return f"{pkmn.name_and_type} was **{status.past_tense}**."
			elif self.name == "FaintTransaction":
				target = util.resolve_target(context, Target(**self.args["Target"]))

				return f"{target.pokemon.name_and_type} **fainted**."
			elif self.name == "EndBattleTransaction":
				return f"The battle has ended."
			elif self.name == "MoveFailTransaction":
				user = util.resolve_target(context, Target(**self.args["User"])).pokemon
				reason = MoveFailReason(self.args["Reason"])

				if reason == MoveFailReason.miss:
					msg = "**missed**"
				elif reason == MoveFailReason.dodge:
					msg = "was **dodged**"
				else:
					msg = "**failed**"
				return f"{user.name_and_type} {msg}."
			elif self.name == "ModifyStatTransaction":
				pkmn = util.resolve_target(context, Target(**self.args["Target"])).pokemon
				stat = Stat(self.args['Stat'])
				stages = self.args['Stages']

				if stages > 0:
					direc = "increased"
				else:
					direc = "decreased"
				return f"{pkmn.name_and_type}'s {stat} {direc} by {abs(stages)}."
			elif self.name == "PPTransaction":
				move = Move(**self.args["Move"])
				if self.args["Amount"] > 0:
					return f"{move.name_and_type} restored {self.args['Amount']} PP."
				else:
					return f"{move.name_and_type} lost {abs(self.args['Amount'])} PP."
			elif self.name == "UseMoveTransaction":
				tuser = util.resolve_target(context, Target(**self.args["User"]))
				target = util.resolve_target(context, Target(**self.args["Target"]))
				move = Move(**self.args["Move"])
				return f"{tuser.pokemon.name_and_type} used {move.name_and_type} on {target.pokemon.name_and_type}!"
			elif self.name == "SendOutTransaction":
				target = util.resolve_target(context, Target(**self.args["Target"]))
				return f"{target.pokemon.name_and_type} was sent out."
			elif self.name == "ImmobilizeTransaction":
				target = util.resolve_target(context, Target(**self.args["Target"]))
				status = StatusCondition(self.args["StatusEffect"])
				return f"{target.pokemon.name_and_type} is **{status.past_tense}**!"
			elif self.name == "CureStatusTransaction":
				target = util.resolve_target(context, Target(**self.args["Target"]))
				status = StatusCondition(self.args["StatusEffect"])
				return f"{target.pokemon.name_and_type} is no longer **{status.past_tense}**!"
			elif self.name == "WeatherTransaction":
				weather = BattleWeather(self.args["Weather"])
				if weather == BattleWeather.ClearSkies:
					return "The weather is now **clear**."
				elif weather == BattleWeather.HarshSunlight:
					return "The **sunlight turned harsh**."
				elif weather == BattleWeather.Rain:
					return "It started to **rain**."
				elif weather == BattleWeather.Sandstorm:
					return "A **sandstorm** brewed."
				elif weather == BattleWeather.Hail:
					return "It started to **hail**."
				elif weather == BattleWeather.Fog:
					return "The **fog** is deep..."
				else:
					return f"The weather changed to **{weather}**."
			else:
				return f"TODO: {self.name}<{self.type}> {self.args}"
		except Exception as e:
			log.error(f"Failed to pretty print transaction: {type(e)} {e}")
			return f"Failed: {self.name}<{self.type}> {self.args}"