示例#1
0
func Example() {
	check := nagiosplugin.NewCheck()
	// Make sure the check always (as much as possible) exits with
	// the correct output and return code if we terminate unexpectedly.
	defer check.Finish()
	// (If the check panicked on the next line, it'd exit with a
	// default UNKNOWN result.)
	//
	// Our check is testing the internal consistency of the
	// universe.
	value := math.Pi
	// We add a dimensionless metric with a minimum of zero, an
	// unbounded maximum, a warning threshold of 4000.0 and a
	// critical threshold of 9000.0 (for graphing purposes).
	check.AddPerfDatum("badness", "", value, 0.0, math.Inf(1), 4000.0, 9000.0)
	// Add an OK check result as the universe appears sane.
	check.AddResult(nagiosplugin.OK, "Everything looks shiny from here, cap'n")
	// We potentially perform more checks and add more results here;
	// if there's more than one, the highest result will be the one
	// returned (in ascending order OK, WARNING, CRITICAL, UNKNOWN).

	// This will print:
	// OK: Everything looks shiny from here, cap'n | badness=3.141592653589793;4000;9000;0;
}
func main() {

	flag.Parse()

	start := time.Now()

	u, err := url.Parse(fmt.Sprintf("http://%s:%d", *host, *port))
	if err != nil {
		log.Fatal(err)
	}

	conf := client.Config{
		URL:      *u,
		Username: *user,
		Password: *password,
		Timeout:  time.Duration(*timeout) * time.Millisecond,
	}

	check := nagiosplugin.NewCheck()
	defer check.Finish()

	con, err := client.NewClient(conf)
	if err != nil {
		check.AddResult(nagiosplugin.UNKNOWN, "Can't connect to database")
		log.Fatal(err)
	}

	q := client.Query{
		Command:  *query,
		Database: *db,
	}

	if response, err := con.Query(q); err == nil {
		if response.Error() != nil {
			check.AddResult(nagiosplugin.UNKNOWN, "Can't execute query")
			log.Fatal(err)
		}

		result, err := (response.Results[0].Series[0].Values[0][1].(json.Number)).Float64()

		duration := time.Since(start)

		if err != nil {
			check.AddResult(nagiosplugin.UNKNOWN, "Error parsing result")
		}

		message := fmt.Sprintf("Got %v in %v", result, duration)

		check.AddPerfDatum("value", "", result)

		if *warning != "" {
			warnRange, err := nagiosplugin.ParseRange(*warning)
			if err != nil {
				check.AddResult(nagiosplugin.UNKNOWN, "Error parsing warning range")
			}
			if warnRange.Check(result) {
				check.AddResult(nagiosplugin.WARNING, message)
			}
		}

		if *critical != "" {
			criticalRange, err := nagiosplugin.ParseRange(*critical)
			if err != nil {
				check.AddResult(nagiosplugin.UNKNOWN, "Error parsing critical range")
			}

			if criticalRange.Check(result) {
				check.AddResult(nagiosplugin.CRITICAL, message)
			}
		}
		check.AddResult(nagiosplugin.OK, message)
	}
}