Exemplo n.º 1
0
func TestPGReportToDB(t *testing.T) {
	var re Element
	var rs Set
	var prr Runner
	var pghr Handler
	cxn := database.GetPGConnection(conf.DBURI())

	re = SimpleRE{[]string{"Something", "Nothing", "Mine", "Yours"}}
	var templateSimplePostgres = `
	CREATE TABLE IF NOT EXISTS {{metadata.schema}}.{{metadata.table}}("something" text, "nothing" text, "mine" text, "yours" text);
	{% for element in elements %}
	INSERT INTO "{{metadata.schema}}"."{{metadata.table}}" ("something", "nothing", "mine", "yours") VALUES ('{{ element.Something }}', '{{ element.Nothing }}', '{{ element.Mine}}', '{{ element.Yours }}' );
	{% endfor %}
	`

	prr = NewPongo2ReportRunnerFromString(templateSimplePostgres)
	pghr = PGHandler{cxn}
	//pghr = PrintHandler{}

	elements := []Element{re, re}
	metadata := map[string]interface{}{
		"test":   "json",
		"schema": "public",
		"table":  "something",
	}
	rs = Set{elements, metadata}

	reader, err := prr.ReportReader(rs)
	err = pghr.HandleReport(reader)
	if err != nil {
		t.Fatalf("error writing report\n%s", err)
	}
}
Exemplo n.º 2
0
func TestLogLevelingFiltering(t *testing.T) {
	cxn := database.GetPGConnection(conf.DBURI())
	healthChecks, _ := healthcheck.ReadHealthCheckYAMLFromFile("healthcheck/healthchecksAll.yml")
	results, _ := healthChecks.PreformHealthChecks(cxn)
	var elements []report.Element
	for _, val := range results {
		elements = append(elements, val)
	}
	metadata := map[string]interface{}{
		"name": healthChecks.Name,
	}
	originalReportSet := report.Set{Elements: elements, Metadata: metadata}
	TestLogLevelResults := map[string]int{
		"Debug": 6,
		"Info":  5,
		"Warn":  4,
		"Error": 2,
		"Fatal": 1,
	}

	for _, level := range report.LogLevelArray {
		log.Infof("Report Filter LogLevel %v", level)
		logFilteredSet := report.FilterReportSet(originalReportSet, level)
		prr := report.JSONReportRunner{}
		reader, _ := prr.ReportReader(logFilteredSet)
		phr := report.PrintHandler{}
		_ = phr.HandleReport(reader)

		if len(logFilteredSet.GetElementArray()) != TestLogLevelResults[level] {
			t.Fatalf("wrong number of healthchecks in report")
		}
	}

}
Exemplo n.º 3
0
func TestRunningBasicChecks(t *testing.T) {
	cxn := database.GetPGConnection(conf.DBURI())
	healthChecks, _ := ReadHealthCheckYAMLFromFile("healthchecksTest.yml")
	healthChecks.RunHealthChecks(cxn)

	for _, hc := range healthChecks.Tests {
		if !hc.Passed {
			log.Error("Basic HealthCheck Test Failed")
			t.Fail()
		}
	}
}
Exemplo n.º 4
0
func TestEvaluatingInvalidChecks(t *testing.T) {
	cxn := database.GetPGConnection(conf.DBURI())
	healthChecks, _ := ReadHealthCheckYAMLFromFile("healthchecksInvalid.yml")
	results, err := healthChecks.PreformHealthChecks(cxn)

	if err == nil {
		log.Error("Healthchecks did not throw an error, but should have")
		t.Fail()
	}
	if len(results) != 2 {
		log.Error("Healthcheck results had the wrong length")
		t.Fail()
	}
}
Exemplo n.º 5
0
func TestEvaluatingBasicChecks(t *testing.T) {
	cxn := database.GetPGConnection(conf.DBURI())
	healthChecks, _ := ReadHealthCheckYAMLFromFile("healthchecksTest.yml")
	results, err := healthChecks.PreformHealthChecks(cxn)

	if err != nil {
		log.Error(err)
		t.Fail()
	}
	if len(results) != 3 {
		log.Error("Healthchecks results had the wrong length")
		t.Fail()
	}
	for _, result := range results {
		if !result.Passed {
			log.Error("Basic HealthCheck Test Failed")
			t.Fail()
		}
	}
}
Exemplo n.º 6
0
func TestEvaluatingIncompleteChecks(t *testing.T) {
	cxn := database.GetPGConnection(conf.DBURI())
	healthChecks, ferr := ReadHealthCheckYAMLFromFile("healthchecksIncomplete.yml")

	if ferr == nil {
		log.Error("Reading Healthcheck file did not throw an error, but should have")
		t.Fail()
	}

	healthChecks.RejectBadHealthChecks()
	results, err := healthChecks.PreformHealthChecks(cxn)

	if err != nil {
		log.Error("Evaluating Healthchecks threw an error")
		t.Fail()
	}

	if len(results) != 1 {
		log.Error("Healthcheck results had the wrong length")
		t.Fail()
	}
}
Exemplo n.º 7
0
func TestCLI_PG_Healthchecks(t *testing.T) {

	//clear hctest
	cxn := database.GetPGConnection(conf.DBURI())
	result, err := cxn.Exec("DROP TABLE IF EXISTS public.hctest")
	if err != nil {
		t.Fatalf("error dropping public.hctest\n%s", err)
	}

	args := []string{"rhobot", "healthchecks", "healthcheck/healthchecksTest.yml",
		"--schema", "public", "--table", "hctest"}
	os.Args = args
	main()

	//make sure hctest only has 3 rows
	row, err := cxn.Query("SELECT count(*) FROM public.hctest;")
	defer row.Close()
	if err != nil {
		t.Fatalf("error selecting public.hctest\n%s", err)
	} else {

		if row.Next() {
			var count int
			err = row.Scan(&count)

			if count != 3 {
				t.Fatal("public.hctest count should have been 3")
			}

		} else {
			t.Fatalf("no results in selecting public.hctest\n%s", err)
		}

	}

	log.Info(result)
}
Exemplo n.º 8
0
func TestPostgresHealthCheckReporting(t *testing.T) {
	cxn := database.GetPGConnection(conf.DBURI())
	healthChecks, _ := healthcheck.ReadHealthCheckYAMLFromFile("healthcheck/healthchecksAll.yml")
	results, _ := healthChecks.PreformHealthChecks(cxn)
	var elements []report.Element
	for _, val := range results {
		elements = append(elements, val)
	}
	metadata := map[string]interface{}{
		"name":      healthChecks.Name,
		"schema":    "public",
		"table":     "healthchecks",
		"timestamp": time.Now().Format(time.ANSIC),
	}
	rs := report.Set{Elements: elements, Metadata: metadata}

	prr := report.NewPongo2ReportRunnerFromString(healthcheck.TemplateHealthcheckPostgres)
	pgr := report.PGHandler{Cxn: cxn}
	reader, err := prr.ReportReader(rs)
	err = pgr.HandleReport(reader)
	if err != nil {
		t.Fatalf("error writing report to PG database\n%s", err)
	}
}
Exemplo n.º 9
0
func healthcheckRunner(config *config.Config, healthcheckPath string, reportPath string, emailListPath string, hcSchema string, hcTable string) {
	healthChecks, err := healthcheck.ReadHealthCheckYAMLFromFile(healthcheckPath)
	if err != nil {
		log.Fatal("Failed to read healthchecks: ", err)
	}
	cxn := database.GetPGConnection(config.DBURI())

	results, HCerrs := healthChecks.PreformHealthChecks(cxn)
	numErrors := 0
	fatal := false
	for _, hcerr := range HCerrs {
		if strings.Contains(strings.ToUpper(hcerr.Err), "FATAL") {
			fatal = true
		}
		if strings.Contains(strings.ToUpper(hcerr.Err), "ERROR") {
			numErrors = numErrors + 1
		}
	}

	var elements []report.Element
	for _, val := range results {
		elements = append(elements, val)
	}

	// Make Templated report
	metadata := map[string]interface{}{
		"name":      healthChecks.Name,
		"db_name":   config.PgDatabase,
		"footer":    healthcheck.FooterHealthcheck,
		"timestamp": time.Now().Format(time.ANSIC),
		"status":    healthcheck.StatusHealthchecks(numErrors, fatal),
		"schema":    hcSchema,
		"table":     hcTable,
	}
	rs := report.Set{Elements: elements, Metadata: metadata}

	// Write report to file
	if reportPath != "" {
		prr := report.NewPongo2ReportRunnerFromString(healthcheck.TemplateHealthcheckHTML)
		reader, _ := prr.ReportReader(rs)
		fhr := report.FileHandler{Filename: reportPath}
		err = fhr.HandleReport(reader)
		if err != nil {
			log.Error("error writing report to PG database: ", err)
		}
	}

	// Email report
	if emailListPath != "" {
		prr := report.NewPongo2ReportRunnerFromString(healthcheck.TemplateHealthcheckHTML)
		df, err := report.ReadDistributionFormatYAMLFromFile(emailListPath)
		if err != nil {
			log.Fatal("Failed to read distribution format: ", err)
		}

		for _, level := range report.LogLevelArray {

			subjectStr := healthcheck.SubjectHealthcheck(healthChecks.Name, config.PgDatabase, config.PgHost, level, numErrors, fatal)

			logFilteredSet := report.FilterReportSet(rs, level)
			reader, _ := prr.ReportReader(logFilteredSet)
			recipients := df.GetEmails(level)

			if recipients != nil && len(recipients) != 0 && len(logFilteredSet.Elements) != 0 {
				log.Infof("Send %s to: %v", subjectStr, recipients)
				ehr := report.EmailHandler{
					SMTPHost:    config.SMTPHost,
					SMTPPort:    config.SMTPPort,
					SenderEmail: config.SMTPEmail,
					SenderName:  config.SMTPName,
					Subject:     subjectStr,
					Recipients:  recipients,
					HTML:        true,
				}
				err = ehr.HandleReport(reader)
				if err != nil {
					log.Error("Failed to email report: ", err)
				}
			}
		}
	}

	if hcSchema != "" && hcTable != "" {
		prr := report.NewPongo2ReportRunnerFromString(healthcheck.TemplateHealthcheckPostgres)
		pgr := report.PGHandler{Cxn: cxn}
		reader, err := prr.ReportReader(rs)
		err = pgr.HandleReport(reader)
		if err != nil {
			log.Errorf("Failed to save healthchecks to PG database\n%s", err)
		}
	}

	// Bad Exit
	if HCerrs != nil {
		log.Fatal("Healthchecks Failed:\n", spew.Sdump(HCerrs))
	}
}